It would be nice to be able to use a has_many association through a named scope. E.g. if a user has many posts, and a post has many comments, one can use a named_scope in posts to define a scope for recent posts and a has_many association for users to get all comments of a user through his/her posts. However, you cannot get all comments on recent posts, because that'd require to do something like :through => 'posts.recent', which obviously doesn't work.
class Comment < ActiveRecord::Base
belongs_to :post
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
named_scope :recent, lambda { { :conditions => ['created_at > ?', 1.week.ago] } }
end
class User < ActiveRecord::Base
has_many :posts
# all comments of all posts of a user
has_many :comments, :through => :posts
# Doesn't work: all comments of all recent posts of a user
#has_many :comments_on_recent_posts, :through => 'posts.recent', :source => :comments
end
Sure, one could use :conditions on the has_many association to scope the find, but that would mean that the advantage of the named_scope (defining the scope conditions in the model that it applies to) would be gone.
So, it would be nice if has_many :through could also work with a named scope, maybe by introducing a new option named :scope or :named_scope or :through_scope:
has_many :comments_on_recent_posts, :through => :posts, :through_scope => :recent, :source => :comments