在 Rails 2.3 中,如何从二阶 has_many 关联中检索对象集合?
我有一个合作伙伴模型,它有_并且属于_许多项目,而每个项目都有_许多站点。我想检索给定合作伙伴的所有网站(目前对中间的项目不感兴趣)。
我已经通过 Site 模型上的named_scope 以及包装对 Site 命名范围的调用的project.sites 实例方法完成了我需要的操作,如下所示:
class Partner < ActiveRecord::Base
has_and_belongs_to_many :projects
def sites
Site.for_partner_id(self.id)
end
end
class Project < ActiveRecord::Base
has_many :sites
end
class Site < ActiveRecord::Base
belongs_to :project
named_scope :for_partner_id, lambda {|partner_id|
{ :include=>{:project=>:partners},
:conditions=>"partners.id = #{partner_id}"
}
}
end
现在,给定一个合作伙伴实例,我可以调用partner.sites 并获取支持与合作伙伴关联的所有站点的集合。这正是我想要的行为,但我想知道是否有另一种方法可以仅使用 activerecord 关联而不使用命名范围来实现此目的?
I have a Partner model that has_and_belongs_to_many Projects, while each Project has_many Sites. I want to retrieve all sites for a given partner (and am not interested in the projects in between at the moment).
I have accomplished what I need through a named_scope on the Site model, and a project.sites instance method that wraps a call to the Site named scope, as follows:
class Partner < ActiveRecord::Base
has_and_belongs_to_many :projects
def sites
Site.for_partner_id(self.id)
end
end
class Project < ActiveRecord::Base
has_many :sites
end
class Site < ActiveRecord::Base
belongs_to :project
named_scope :for_partner_id, lambda {|partner_id|
{ :include=>{:project=>:partners},
:conditions=>"partners.id = #{partner_id}"
}
}
end
Now, given a partner instance, I can call partner.sites and get back a collection of all sites associated with the partner. This is precisely the behavior I want, but I'm wondering if there's another way to do this using only activerecord associations, without the named scope?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我在这里遇到了类似的深层嵌套查询/集合问题(在有人回答我的 4 个问题之前,我不得不威胁要重复数据,聪明):
在模型中重复数据以满足在集合中使用德米特定律是否合适?
技巧是这个 gem http://rubygems.org/gems/nested_has_many_through 可以执行如下操作:
这极大地简化了我的查询和集合。我希望你能找到问题的答案,这是一个很难的问题!
I had a similar deep nesting query/collection problem here (I had to threaten to repeat data before anyone would answer my 4 questions, clever):
Is it appropriate to repeat data in models to satisfy using law of demeter in collections?
The trick is this gem http://rubygems.org/gems/nested_has_many_through which can do something like this:
This has super-simplified my queries and collections. I hope you find an answer to your problem, it's a tough one!