为什么 ARel 查询返回为 ActiveRecord::Relation 类而不是父类?
我有一个类:
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
我做错了什么?
I have a class:
class Technician < ActiveRecord::Base
scope :named, lambda {|name| where(["first_name LIKE ?", "%#{name}%"])}
end
In rails console, when I do the following query:
technician = Technician.named("john")
technician.class => ActiveRecord::Relation and not Technician
this matters because I get a no method error when I try to access the class attributes:
technician.id => no method error
what am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Arel 返回
ActiveRecord::Relation
,这样它就可以将执行推迟到最后一刻,并提供更好的可组合性。Technician.named("john").first
而不是Technician.named("john")
来获取technician
。Arel returns
ActiveRecord::Relation
so that it can defer the execution to the last moment and provide better composability.Technician.named("john").first
instead ofTechnician.named("john")
to get thetechnician
.