Ruby on rails 未按预期运行的Rails

Ruby on rails 未按预期运行的Rails,ruby-on-rails,ruby-on-rails-4,rails-activerecord,Ruby On Rails,Ruby On Rails 4,Rails Activerecord,我正在尝试使用rails中的where检索一组项。如果我检索我看到的所有内容: 但出于某种原因,这是查询id,而不是启动_站,因此找不到任何东西,但我不知道为什么 更新1 感谢David的评论,我发现这个问题是由我在模型上有一个名为start_station的属性引起的,该属性是一个整数,但也有一个名为start_station的has_one关系 如果我删除此关系或将其重命名,则以下各项建议将按预期效果运行: JourneyLeg.where(:start_station => 24)

我正在尝试使用rails中的where检索一组项。如果我检索我看到的所有内容:

但出于某种原因,这是查询id,而不是启动_站,因此找不到任何东西,但我不知道为什么

更新1

感谢David的评论,我发现这个问题是由我在模型上有一个名为start_station的属性引起的,该属性是一个整数,但也有一个名为start_station的has_one关系

如果我删除此关系或将其重命名,则以下各项建议将按预期效果运行:

JourneyLeg.where(:start_station => 24)
JourneyLeg.where(start_station: 24)

这应该基于

我已经在本地应用程序的模型Article中尝试了这一点,它遵循where works Rails 4.2.2、Ruby 2.0.0p247的变体

变式1

变式2

变式3

试试这个


JourneyLeg.wherestart_station='24'

这会引发一个错误语法错误,意外的“:”,预期=>您是否尝试使用JourneyLeg.where{start_station=>24}?我将检查syntax这会给出一个语法错误,因为“start_station”后面有空格-正确的语法是JourneyLeg.wherestart_station:24,它相当于JourneyLeg.where:start_station=>24是start_station是整数还是字符串?也许你需要使用JourneyLeg.where start_station:'24'你可以试试JourneyLeg.where{:start_station=>24}你使用的是哪个版本的ruby和rails?你有没有在模型中定义的方法,它会被ActiveRecord覆盖start_station的定义?硬编码sql语句显然会给你想要的查询,但这并不能解决Rails为何表现出这种错误行为的问题。
2.2.2 :028 > JourneyLeg.where(:start_station => 24)
JourneyLeg Load (0.1ms)  SELECT "journey_legs".* FROM "journey_legs" WHERE "journey_legs"."id" = ?  [["start_station", 24]]
=> #<ActiveRecord::Relation []> 
has_one :start_station, :class_name => "Station", :primary_key => "start_station", :foreign_key => "id"
JourneyLeg.where(:start_station => 24)
JourneyLeg.where(start_station: 24)
JourneyLeg.where({:start_station => 24})
irb(main):006:0> Article.where({id: 2})
  Article Load (1.0ms)  SELECT "articles".* FROM "articles" WHERE "articles"."id" = ?  [["id", 2]]
=> #<ActiveRecord::Relation [#<Article id: 2, title: "World", text: nil, created_at: "2015-07-25 21:09:16", updated_at: "2015-07-25 21:09:16">]>
irb(main):009:0> Article.where({:id => 2})
  Article Load (0.0ms)  SELECT "articles".* FROM "articles" WHERE "articles"."id" = ?  [["id", 2]]
=> #<ActiveRecord::Relation [#<Article id: 2, title: "World", text: nil, created_at: "2015-07-25 21:09:16", updated_at: "2015-07-25 21:09:16">]>
irb(main):010:0> Article.where(id: 2)
  Article Load (0.0ms)  SELECT "articles".* FROM "articles" WHERE "articles"."id" = ?  [["id", 2]]
=> #<ActiveRecord::Relation [#<Article id: 2, title: "World", text: nil, created_at: "2015-07-25 21:09:16", updated_at: "2015-07-25 21:09:16">]>