2016-03-06 107 views
0

我有以下型号:Rails的activerecords嵌套包括

class BusinessProcess < ActiveRecord::Base 
    has_many :todos 
end 

class Todo < ActiveRecord::Base 
    has_one :row 
end 

class Row < ActiveRecord::Base 
    has_many :users 
end 

我怎么能算的rowsBusinessProcess具有对特定user行数?

是这样的:

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

+0

请问您可以添加ActiveRecord类的代码吗?至少是协会。顺便说一下* @processProcess *不是很Rubyish。 –

+0

我一直在看你的问题。你能澄清一件事吗?在'Row'中,你有'has_many:users'。这意味着,我认为'User'应该有一个'belongs_to:row'。那么看起来像'User'只能有一个'Row'。它是否正确?看起来很奇怪,因为'User'可能会有很多行,在这种情况下,您需要一个多对多的连接模型。谢谢。 – jvillian

回答

0

@ businessProcess.todos.includes(:行=>:用户)。凡( “?users.id =”,1).Count之间

+0

如果您只是要计算BusinessProcess中的行数,这不是一个适当的解决方案,因为您也实例化所有Todo对象,Row对象和User对象。这很慢。 –

+0

在这种情况下行是一个模型,而不是一个普通的行。我想要的是通过待办事项统计属于BusinessProcess的行。我看不到其他方式。你做? – user3618353

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 

也许你也可以认为移动其中条件为的范围,但更多的是责任的thingie。 你也可以阅读关于ARel作为替代:The N+1 problem and ARel