Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reusing named_scope to define another named_scope

The problem essence as I see it

One day, if I'm not mistaken, I have seen an example of reusing a named_scope to define another named_scope. Something like this (can't remember the exact syntax, but that's exactly my question):

named_scope :billable, :conditions => ...
named_scope :billable_by_tom, :conditions => {
    :billable => true, 
    :user => User.find_by_name('Tom')
}

The question is: what is the exact syntax, if it's possible at all? I can't find it back, and Google was of no help either.

Some explanations

Why I actually want it, is that I'm using Searchlogic to define a complex search, which can result in an expression like this:

Card.user_group_managers_salary_greater_than(100)

But it's too long to be put everywhere. Because, as far as I know, Searchlogic simply defines named_scopes on the fly, I would like to set a named_scope on the Card class like this:

named_scope from_big_guys, { user_group_managers_salary_greater_than(100) }

- this is where I would use that long Searchlogic method inside my named_scope. But, again, what would be the syntax? Can't figure it out.

Resume

So, is named_scope nesting (and I do not mean chaining) actually possible?

like image 952
mxgrn Avatar asked Mar 14 '10 20:03

mxgrn


1 Answers

You can use proxy_options to recycle one named_scope into another:

class Thing
  #...
  named_scope :billable_by, lambda{|user| {:conditions => {:billable_id => user.id } } }
  named_scope :billable_by_tom, lambda{ self.billable_by(User.find_by_name('Tom').id).proxy_options }
  #...
end

This way it can be chained with other named_scopes.

I use this in my code and it works perfectly.

I hope it helps.

like image 162
Oinak Avatar answered Sep 30 '22 12:09

Oinak