[英]Rails ActiveRecord Multiple Levels of Association
I'm having a little trouble with querying multiple tables with different types of association. 我在查询具有不同类型关联的多个表时遇到了一些麻烦。 Can someone please point me in the right direction?
有人可以指点我正确的方向吗?
class Sale < ActiveRecord::Base
has_many :items, :dependent => :destroy
end
class Item < ActiveRecord::Base
belongs_to :sale, :dependent => :destroy
has_many :images, :dependent => :destroy
end
class Image < ActiveRecord::Base
belongs_to :item, :dependent => :destroy
end
What would be the query to get all items relating to a sale with the ID 1, and then loop through all the images relating to each item returned? 获取与ID为1的销售相关的所有项目的查询是什么,然后循环浏览与返回的每个项目相关的所有图像?
Thanks for your help. 谢谢你的帮助。
You can define :through => :something
in a has_many
association 您可以定义
:through => :something
has_many
关联中的:through => :something
class Sale < ActiveRecord::Base
has_many :items, :dependent => :destroy
has_many :images, :through => :items
end
and then simply query 然后简单地查询
Sale.find(1).images
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.