Rails activerecords与嵌套包含

时间:2016-03-06 19:51:41

标签: ruby-on-rails activerecord

我有以下型号:

class BusinessProcess < ActiveRecord::Base
  has_many :todos
end

class Todo < ActiveRecord::Base
  has_one :row
end

class Row < ActiveRecord::Base
  has_many :users
end

如何计算特定rows上有行的BusinessProcessuser的数量?

类似的东西:

@businessProcess.todos.includes(XXX).where(users.id=?,1).count

2 个答案:

答案 0 :(得分:0)

@ businessProcess.todos.includes(:row =&gt;:users).where(“users.id =?”,1).count

答案 1 :(得分:0)

根据您的协会,我宁愿选择加入表格,如:

class Todo < ActiveRecord::Base
  has_one :row
  has_many: users, through: :row

  scope :by_user_id, ->(user_id) { 
    joins(:users).where("users.id = ?", user_id)
  }
end

然后:

@business_process.todos.by_user_id(1).count

也许您也可以考虑将 where 条件移动到 Row 的范围内,但这更像是一种责任感。 您还可以阅读有关ARel的替代方案:The N+1 problem and ARel