【问题标题】:Rails 3, Active Record query returns ActiveRecord::Relation object, instead of objectsRails 3,Active Record 查询返回 ActiveRecord::Relation 对象,而不是对象
【发布时间】:2010-12-13 06:55:20
【问题描述】:

我觉得这是一个简单的问题,因为我对新的 ActiveRecord 查询接口有误解,但举这个例子:

>> Category.first.recipes
=> [ ... ] # array of recipes

但是:

>> Category.where(:id => 1).recipes
=> NoMethodError: undefined method `recipes' for #<ActiveRecord::Relation:0x000001033dc9e0>

这里发生了什么?为什么我的where 方法返回一个ActiveRecord::Relation 对象?如何在此处从查询中检索对象?

【问题讨论】:

    标签: ruby-on-rails activerecord ruby-on-rails-3


    【解决方案1】:

    这其实是故意的。

    Category.where(:id => 1)
    # Is Equivalent to Category.all(:conditions => {:id => 1}})
    Category.where(:id => 1).first
    # Is equivalent of Category.first(:conditions => {:id => 1}})
    

    只有在调用 first、each 等特殊方法时才会检索对象。这称为延迟加载,当您想要缓存视图时非常有用。阅读更多关于为什么here

    【讨论】:

    • 投反对票,因为它不等同。 where 返回 ActiveRecord::Relation,其余返回 Array 或 Model.class
    • 在上下文中是等价的。这就是为什么我提到延迟加载。但是是的,.where.all 是等价的。
    【解决方案2】:
    Category.where(:id => 1).recipes
    

    返回一个数组。如果你只是做Category.where(:id =&gt; 1).first.recipes 它应该可以工作。

    【讨论】:

      【解决方案3】:

      但是,如果您只是针对 id 执行 where,请使用 find 方法 Category.find(1) 将返回一个 Category 对象。
      所以:
      Category.find(1).recipes

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-02-26
        • 2021-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多