当我运行ActiveRecord查询时,Rails控制台似乎将LIMIT 1
附加到我的查询中。
所以我有sheet
has_many
slots
。当我查询Slot.find_by(sheet_id: 96)
时,我得到:
Slot Load (2.3ms) SELECT "slots".* FROM "slots" WHERE "slots"."sheet_id" = ? LIMIT 1 [["sheet_id", 96]]
=> #<Slot id: 153, label: "Foo", name: "Foo", email: "", phone: "", comments: "Fighters", sheet_id: 96, created_at: "2015-04-30 14:28:47", updated_at: "2015-04-30 14:28:47">
但是当我查询Sheet.find(96).slots
时:
Sheet Load (10.0ms) SELECT "sheets".* FROM "sheets" WHERE "sheets"."id" = ? LIMIT 1 [["id", 96]]
Slot Load (4.6ms) SELECT "slots".* FROM "slots" WHERE "slots"."sheet_id" = ? [["sheet_id", 96]]
=> #<ActiveRecord::Associations::CollectionProxy [#<Slot id: 153, label: "Foo", name: "Foo", email: "", phone: "", comments: "Fighters", sheet_id: 96, created_at: "2015-04-30 14:28:47", updated_at: "2015-04-30 14:28:47">, #<Slot id: 154, label: "Bar", name: "James", email: "", phone: "", comments: "Foobar", sheet_id: 96, created_at: "2015-04-30 14:28:47", updated_at: "2015-04-30 14:28:47">, ... >
答案 0 :(得分:2)
你必须Slot.find_all_by_sheet_id(96)
编辑以上代码应该有效。虽然我使用Rails 4.1.8。也请尝试以下:
Slot.where(:sheet_id => 338)
答案 1 :(得分:0)
find_by
方法始终返回单个结果。
如果您想获得特定工作表的所有插槽,可以选择以下几种方法:
Sheet.find(96).slots
或更有可能@sheet.slots
如果您已找到该表
Slot.where(sheet_id: 96)
也可以使用
要清楚,这与Rails控制台无关,而与.find_by
方法有关。