Rails 急切加载和条件
我设置了以下关联
class bookinghdr
belongs_to :agent
end
class bookingitem
belongs_to :bookinghdr, :include => agent
end
所以我期望能够执行以下操作:
named_scope :prepay, :include=>["bookinghdr"], :conditions => ["bookinghdr.agent.agenttype = 'PP'"]
并在我的控制器中执行以下操作:
b = Bookingitem.prepay
但这给了我一个 ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'bookinghdr.agent.agenttype'
但是如果我不包含条件子句,那么我会得到一个可以执行的记录集:
b = Bookingitem.prepay
b[0].bookinghdr.agent.agenttype
没有任何错误!
我不想获取所有记录,然后迭代它们以查找其代理具有“PP@”标志的记录。我希望 AR 能为我做到这一点。
有人对如何实现这一目标有任何想法吗?
I have the following associations set up
class bookinghdr
belongs_to :agent
end
class bookingitem
belongs_to :bookinghdr, :include => agent
end
So I was expecting to be able to do the following:
named_scope :prepay, :include=>["bookinghdr"], :conditions => ["bookinghdr.agent.agenttype = 'PP'"]
and in my controller do:
b = Bookingitem.prepay
But that gives me a ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'bookinghdr.agent.agenttype'
However if I don't include the conditions clause then I get a recordset on which I can do:
b = Bookingitem.prepay
b[0].bookinghdr.agent.agenttype
without any error!
I don't want to have to get all the records and then iterate over them to find the ones whose agent has a 'PP@ flag. I was hoping that AR would do that for me.
Anybody got any ideas on how to achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的问题表明您尚未完全理解关联和命名范围的工作原理。由于我无法从您的问题中看出哪些部分不清楚,因此我建议您阅读协会基础指南 http://guides.rubyonrails.org/v2.3.11/association_basics.html。这应该可以让您快速了解想要实现的概念。阅读完指南后,一切都应该有意义了。
Your question shows that you have not yet fully understood how associations and named scopes work. Since I cannot tell from your question what parts aren't clear, I suggest you read the Association Basics guide at http://guides.rubyonrails.org/v2.3.11/association_basics.html. This should bring you up to speed regarding the concepts you want to implement. After you have read the guide it should all make sense.