Is it possible to have a scope with optional arguments?
I used scope :name, ->(arg1, arg2 = value) { ... }
a few weeks ago, it worked well, if my memory's correct. To use with ruby 1.9+
Ruby 1.9 extended blocks to have the same features as methods do (default values are among them):
scope :cheap, lambda{|max_price=20.0| where("price < ?", max_price)}
Call:
Model.cheap
Model.cheap(15)
Yes. Just use a *
like you would in a method.
scope :print_args, lambda {|*args|
puts args
}
You can conditionally modify your scope based on a given argument.
scope :random, ->(num = nil){ num ? order('RANDOM()').limit(num) : order('RANDOM()') }
Usage:
Advertisement.random # => returns all records randomized
Advertisement.random(1) # => returns 1 random record
Or, you can provide a default value.
scope :random, ->(num = 1000){ order('RANDOM()').limit(num) }
Usage:
Product.random # => returns 1,000 random products
Product.random(5) # => returns 5 random products
NOTE: The syntax shown for RANDOM()
is specific to Postgres. The syntax shown is Rails 4.