Ruby on rails ActiveRecord联接获取子对象而不是父对象 我的问题是:

Ruby on rails ActiveRecord联接获取子对象而不是父对象 我的问题是:,ruby-on-rails,ruby,join,activerecord,ruby-on-rails-4,Ruby On Rails,Ruby,Join,Activerecord,Ruby On Rails 4,我有三种模式:公司、父母和孩子 子属于属于公司的父公司 我需要在一个公司内获取某个属性设置为false的所有子级。(父模型有公司id,而子模型没有。) 我正在尝试的是: 我有以下声明: @objects = Parent.joins(:childs).where('parents.company_id' => current_user.company_id, 'childs.foo' => false) 我认为: <!-- This should be a list of c

我有三种模式:公司、父母和孩子

属于
属于公司的父公司

我需要在一个公司内获取某个属性设置为false的所有子级。(父模型有公司id,而子模型没有。)

我正在尝试的是: 我有以下声明:

@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
class公司:毁灭
...
结束
类父级:毁灭
属于:公司
...
结束
类Child
但是,写入
Parent.joins(:childs).
将返回父对象的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::Parents
您可以发布如何设置关联吗?您的子模型中是否有一行
属于:父
?我已编辑了我的问题以显示相关模型。@alex0112-子模型应
属于:父
(单数)而不是
:父
。与母公司相同-它
属于以下公司
(单数)而不是
:公司
。请注意,Rails根据其惯例非常注重使用单数和复数形式。这些不是模型的实际名称,它们只是示例。所以这不会影响代码。然而,为了准确起见,我将编辑我的问题以反映这一点。
Child.joins(:parent).merge(Parent.for_user(current_user)).fooless