【问题标题】:Why ARel query is returned as ActiveRecord::Relation class instead of parent class?为什么 Arel 查询返回为 ActiveRecord::Relation 类而不是父类?
【发布时间】:2010-11-20 17:59:06
【问题描述】:

我有一堂课:

class Technician < ActiveRecord::Base  
  scope :named, lambda {|name| where(["first_name LIKE ?", "%#{name}%"])}  
end  

在 Rails 控制台中,当我执行以下查询时:

technician = Technician.named("john")  
technician.class => ActiveRecord::Relation and not Technician  

这很重要,因为当我尝试访问类属性时出现无方法错误:

technician.id => no method error  

我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    Arel 返回ActiveRecord::Relation,以便它可以将执行推迟到最后一刻并提供更好的可组合性。

    Technician.named("john").first 而不是 Technician.named("john") 以获取 technician。

    【讨论】:

    • 钱德拉...感谢您的帮助。我自己要花很长时间才能弄清楚这种细微差别。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 2014-04-09
    • 2019-08-18
    • 1970-01-01
    • 2023-03-14
    相关资源
    最近更新 更多