Use your named scopes to add conditions to associations! Keep your code DRY and allows eager loading of scoped associations.
Currently this only works for has_many associations, and probably only on Rails 2.2.
class User < ActiveRecord::Base has_many :published_posts, :scope => :published has_many :published_and_approved_posts, :scope => [:published, :approved] end class Post < ActiveRecord::Base named_scope :published, :conditions => { :published => true } named_scope :approved, :conditions => { :approved => true } end
As a Rails plugin:
./script/plugin install git://github.com/kristopher/scoped-associations.git
Prefer gems? Add this to your environment.rb and run the following command.
config.gem 'kristopher-scoped-associations', :lib => 'scoped-associations', :source => 'http://gems.github.com' $ rake gems:install
- Homepage
- License
-
Copyright © 2008 Kristopher Chambers <kristopher.chambers@gmail.com> and Elijah Miller <elijah.miller@gmail.com>, released under the MIT license