Reusing named_scope to define another named_scope

The essence of the problem, as I see it

Once, if I'm not mistaken, I saw an example of reusing named_scope to define another named_scope. Something like this (I don't remember the exact syntax, but this is exactly my question):

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

Question: what kind of syntax, if at all possible? I canโ€™t find it back, and Google didnโ€™t help either.

Some explanation

Why I really want this, I use Searchlogic to define a complex search that can lead to an expression like this:

 Card.user_group_managers_salary_greater_than(100) 

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

 named_scope from_big_guys, { user_group_managers_salary_greater_than(100) } 

- this is where I will use this long Searchlogic method inside my named_scope. But, again, what will be the syntax? Can not understand.

Summary

So, actually embedding scope_name is possible (and I don't mean the chain)?

+7
ruby-on-rails activerecord
source share
5 answers

Refer to this question raised earlier here in SO. To achieve your requirement there is a lighthouse patch.

+1
source share

You can use proxy_options to reinstall 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 

Thus, it can be attached to other named_scopes.

I use this in my code and it works great.

Hope this helps.

+7
source share

Rails 3+

I had the same question, and the good news is that over the past five years, the core Rails team has taken some good steps in the area department.

In Rails 3+, you can do this as you would expect:

 scope :billable, where( due: true ) scope :billable_by_tom, -> { billable.where( user: User.find_by_name('Tom') } Invoice.billable.to_sql #=> "... WHERE due = 1 ..." Invoice.billiable_by_tom.to_sql #=> "... WHERE due = 1 AND user_id = 5 ..." 

FYI, Rails 3+ they renamed named_scope only in scope . I also use Ruby 1.9 syntax.

+1
source share

Chains.

Why not have scope for just Tom at all, for example:

 scope :by_tom, where( user: User.find_by_name('Tom') ) 

And then you can get those entries that are "paid by Tom" with:

 Record.billable.by_tom 
+1
source share

You can use the method to combine the name named_scope, for example:

 def self.from_big_guys self.class.user_group_managers_salary_greater_than(100) end 

This function adds Rails 3 with the new syntax ( http://m.onkey.org/2010/1/22/active-record-query-interface )

0
source share

All Articles