2013-03-04 67 views
0
  • 用户有很多网站
  • 网站有很多控制器
  • 控制器有许多检查

这是我的时刻。添加“其中”条款的Rails“包括”在ActiveRecord的

current_user 
    .sites 
    .joins(:controllers) 
    .where('controllers.inspections_enabled = true') 
    .all(:include => [:controllers => [:inspections]]) 

这给了我:

“所有网站中的控制器被启用,所有控制器和检查”

我想

“所有网站中的控制器开启,并且包括仅具有'inspections_enabled = true'的控制器,其全部是儿童检查“

在此先感谢

+1

你为什么包括'在渴望负荷controllers'。由于您的加入,它已经加载到内存中。我认为你应该是'current_user .sites .joins(:controllers) .where('controllers.inspections_enabled = true') .all(:include => [:inspections])' – codeit 2013-03-04 17:46:05

回答

3

你应该定义已定义的条件的关联,请参阅docs

如果你想急于负载关联的只有一些成员是 通常更自然包括具有 上定义条件的关联它。

你的情况

class Site < ActiveRecord::Base 
    has_many :inspections_enabled_controllers, 
      :class_name => 'Controller', 
      :conditions => ['inspections_enabled = ?', true] 
end 

current_user 
    .sites 
    .joins(:inspections_enabled_controllers) 
    .all(:include => [:inspections])