views:

51

answers:

1

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

+1  A: 

You just need to use

@user.comments.about_x

I personally think there's no need for a named_scope on users model.

But you can add a method instead:

class User < ActiveRecord::Base
   def comments_about_x
      self.comments.about_x
   end
end

and use

@user.comments_about_x
j.