Adding parameter to a scope

Bohn picture Bohn · Mar 5, 2013 · Viewed 35.7k times · Source

I have a ActiveRecord query for example like this:

@result = stuff.limit(10)

where stuff is a active record query with where clauses, order by, etc...

Now I thought why to pass magic numbers like that to the controller? So do you think is it a good practice to define a scope for "limit(10)" and use that instead? and how would the syntax look like?

Answer

Andre Bernardes picture Andre Bernardes · Mar 5, 2013

There are indeed multiple ways of doing such, class methods are one as pointed out by @Dave Newton. If you'd like to use scopes, here's how:

scope :max_records, lambda { |record_limit|
  limit(record_limit)
}

Or with the Ruby 1.9 "stabby" lambda syntax and multiple arguments:

scope :max_records, ->(record_limit, foo_name) {   # No space between "->" and "("
  where(:foo => foo_name).limit(record_limit)
}

If you'd like to know the deeper differences between scopes and class methods, check out this blog post.

Hope it helps. Cheers!