Andrew Wei
Andrew Wei

Reputation: 2080

Adding a "where" clause to Rails "include" in ActiveRecord

This is what I have at the moment.

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

This gives me:

"All sites where a controller is enabled, with all controllers and inspections"

I want

"All sites where a controller is enabled, and include ONLY controllers which has 'inspections_enabled = true', with all it's child inspections"

Thanks in Advance

Upvotes: 0

Views: 1386

Answers (1)

kr1
kr1

Reputation: 7485

you should define an association which has defined conditions, see the docs

If you do want eager load only some members of an association it is usually more natural to include an association which has conditions defined on it.

in your case:

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])

Upvotes: 3

Related Questions