val_to_many
val_to_many

Reputation: 377

Rails - Refer to current object in model

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

Upvotes: 1

Views: 1004

Answers (1)

John Topley
John Topley

Reputation: 115412

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).

Upvotes: 1

Related Questions