Rails 2.3: using another models named_scope inside another named_scope

Posted by mustafi on Stack Overflow See other posts from Stack Overflow or by mustafi
Published on 2010-06-15T13:59:13Z Indexed on 2010/06/15 14:02 UTC
Read the original article Hit count: 115

Filed under:

Hi

Let's say I have two models like so:

class Comment < ActiveRecord::Base
  belongs_to :user
  named_scope :about_x :conditions => "comments.text like '%x%')"
end

class User < ActiveRecord::Base
  has_many :comments
end

How can I add a named_scope to the user model like so

class User < ActiveRecord::Base
  has_many :comments
  named_scope :comments_about_x, :includes => :comments, :comments_named_scope => :about_x
end

Which allows me to do

all_user_comments_about_x = User.comments_about_x

The reasoning is I often need to use the comment models about_x named scope logic but I don't want to have "comments.text like '%x%')" scattered around my code.

I hope this make sense :)

Thank you

© Stack Overflow or respective owner

Related posts about ruby-on-rails