我试图在rails中使用where
检索一组项目。如果我检索all
,我会看到:
2.2.2 :027 > JourneyLeg.all
JourneyLeg Load (0.2ms) SELECT "journey_legs".* FROM "journey_legs"
=> #<ActiveRecord::Relation [
#<JourneyLeg id: 1, start_station: 24, end_station: 25, departure_time: "2000-01-01 06:37:00", arrival_time: "2000-01-01 06:45:00", journey: 6, created_at: "2015-07-25 11:32:42", updated_at: "2015-07-25 11:32:42">,
#<JourneyLeg id: 2, start_station: 25, end_station: 26, departure_time: "2000-01-01 06:46:00", arrival_time: "2000-01-01 06:50:00", journey: 6, created_at: "2015-07-25 11:32:42", updated_at: "2015-07-25 11:32:42">]>
现在我只想返回start_station
为24的项目,因此我使用JourneyLeg.where(:start_station => 24)
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 []>
但由于某些原因,这是查询id
而不是start_station
(因此没有找到任何内容),但我不知道为什么。
更新1
感谢David的评论,我发现这个问题是由于我在名为start_station
的模型上有一个属性,它是一个整数,但也是一个名为{{1}的has_one
关系}}
start_station
如果我删除此关系或将其重命名,则以下内容可按预期方式使用各种建议:
has_one :start_station, :class_name => "Station", :primary_key => "start_station", :foreign_key => "id"
答案 0 :(得分:1)
JourneyLeg.where({:start_station => 24})
我尝试使用我的本地应用程序的模型Article
,跟随where
的变体工作(Rails 4.2.2,Ruby 2.0.0p247)
变体1
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">]>
变体2
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">]>
变体3
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">]>
答案 1 :(得分:1)
试试这个
JourneyLeg.where("start_station = '24'")