我的问题:
我有三个模型:公司、 parent 和 child 。
child belongs_to
parent belongs_to
公司
我需要获取一家公司内某个属性设置为 false 的所有 child 。 (Parent 模型有 company_id 而 Child 模型没有。)
我正在尝试:
我有以下连接:
@objects = Parent.joins(:childs).where('parents.company_id' => current_user.company_id, 'childs.foo' => false)
在我看来:
<!-- This should be a list of child objects -->
<% @objects.each do |obj| %>
<%= obj.foo %>
<% end %>
(foo是子对象的属性)
模型:
class Company < ActiveRecord::Base
has_many :parents, :dependent => :destroy
...
end
class Parent < ActiveRecord::Base
has_many :childs, :dependent => :destroy
belongs_to :company
...
end
class Child < ActiveRecord::Base
belongs_to :parent
...
end
但是,编写 Parent.joins(:childs)...
会返回 Parent 对象的 ActiveRecord 关系。 (当我尝试访问子属性时抛出错误)我需要结束列表是子对象。但我发现这样做很难。
这个问题的一个很好的答案是:
以另一种方式解决了这个问题,这种方式更有意义,而且计算量不会太大。
或显示如何获取子对象而不是父对象的列表/关系的内容。
最佳答案
简单,从子类开始:
Child.joins(:parent).where(parents: {company_id: current_user.company_id}, foo: false)
我可能会建议使用范围/类方法以更简洁的方式完成此任务:
class Parent < ActiveRecord::Base
def self.for_user(user)
where(company_id: user.company_id)
end
end
class Child < ActiveRecord::Base
scope :fooless, ->{where foo: false}
end
现在你可以这样做了:
Child.joins(:parent).merge(Parent.for_user(current_user)).fooless
关于ruby-on-rails - ActiveRecord 联接获取子对象而不是父对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26806905/