You can use default_scope
for this:
class Club < ActiveRecord::Base
has_many :courses, conditions => {:approved => true}
default_scope :include => :courses
end
class Course < ActiveRecord::Base
default_scope :conditions => {:approved => true}
end
Now you can do this:
@club = Club.find(1) # this will eager load approved courses.
Reference:
Article about default_scope
.
Note 1
I changed the courses
assocation in Club
class to select approved courses. In theory, this is not required as the Course
class has a default scope. But, it looks like default scope is not applied for eager loaded queries.
Note 2
I personally would not eager load the Course
objects through default_scope
. Doing it through a default_scope gives you an unobtrusive solution as desired by you.
I would add the include
clause to the find
call to eager load the Course
objects only when it's required.
Note 3
@Ryan Bigg:
Ryan Bates talks about default scopes half way through this his screen cast. He gives an example of using the default scopes to exclude deleted records, i.e.
default_scope :conditions => "delete_at IS NULL"
I consider this use case to be similar. As I perceive the problem, primary operations on the Course model is on approved records and default_scope
with the conditions
option ensures that. To override the default_scope, user can use the with_exclusive_scope
method.
Club.with_exclusive_scope{find(1)}