【问题标题】:Rails console setting limit to one on queriesRails 控制台将查询限制设置为一个
【发布时间】:2015-07-16 16:36:09
【问题描述】:

当我运行 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">, ... >

【问题讨论】:

    标签: ruby-on-rails rails-activerecord rails-console ruby-on-rails-4.2


    【解决方案1】:

    你必须做Slot.find_all_by_sheet_id(96)

    EDIT 上面的代码应该可以工作。虽然我使用的是 Rails 4.1.8。也可以尝试以下操作:

    Slot.where(:sheet_id => 338)
    

    【讨论】:

    • NoMethodError: 未定义的方法`find_all_by_sheet_id'
    • 谢谢阿比。看起来 where 提取所有数据,但 find_by 限制为一条记录。
    【解决方案2】:

    find_by 方法总是返回一个结果。

    如果您想获取特定工作表的所有插槽,有几个选项:

    Sheet.find(96).slots 或更可能是@sheet.slots,如果您已经找到了工作表

    Slot.where(sheet_id: 96) 也可以使用

    需要明确的是,这与 Rails 控制台无关,与 .find_by 方法有关。

    【讨论】:

      猜你喜欢
      • 2014-12-05
      • 1970-01-01
      • 1970-01-01
      • 2011-11-22
      • 2014-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-10-11
      • 1970-01-01
      相关资源
      最近更新 更多