views:

14

answers:

1

I must admit, I am not even sure if I put the question right...

In my app I have a bunch of named scopes to build more efficient finds. The one that I can't get to work is this:

=> I want to find all products in the current category and its descendants. I use the 'ancestry' gem to build the tree, and it provides named scopes on the Class level:

subtree_of(node)        #Subtree of node, node can be either a record or an id

so I thought it would be a good idea to have a named_scope like this:

named_scope :in_tree, :include => :category, :conditions => ['category in (?)', (subtree_of(@category)) ]

or

named_scope :in_tree, :include => :category, :conditions => ['category in (?)', (@category.subtree_ids) ]

Both things work in controllers and helpers, but not in the model ... and when I am not mistaken it comes down to "@category" (I have it defined in the controller) being not available in the model.

Is there a railsy way to make it available?

Thanks for your help!

Val

+1  A: 

It doesn't work in your model because @category is an instance variable that lives within your controllers. You can pass the category into the named scope using a lambda (anonymous function):

named_scope :in_tree, lambda { |category| { :include => :category,
  :conditions => ['category in (?)', (subtree_of(category)) ] }}

or

named_scope :in_tree, lambda { |category| { :include => :category,
  :conditions => ['category in (?)', (category.subtree_ids) ] }} 

Now in your controllers/helpers you can use the named scope using Product.in_tree(@category).

John Topley
Thanks so much John! The second option works like a charm! I actually made a mistake in my question it ends up being this: named_scope :in_tree, lambda { |category| { :include => :category, :conditions => ['categories.id in (?)', (category.subtree_ids) ] }}
val_to_many
Cool, glad you got it working.
John Topley