When and when not to use lambda for named scopes?
I want to understand the effect of a lambda on this named scope:
I have two scopes defined in my model:
scope :credits, lambda { where("comparison_ind != 'PEER'")}
vs
scope :credits, where("comparison_ind != 'PEER'")
What is the difference between the two statements? compare_ind is a column belonging to the same model.
source to share
In Rails 4
always use lambda. Second syntax is wrong in rails 4 and throws an error (undefined method "call" for ActiveRecord :: Relation)
# activerecord/lib/active_record/scoping/named.rb
scope = all.scoping { body.call(*args) }
In Rails 3
scope
the method behaves the same in both cases - it created a new class method credits
. The difference is that when given a lambda, it evaluates that lambda every time this new method is called to get the scope, whereas with a given relationship, it just uses what was passed.
# activerecord/lib/active_record/named_scope.rb
options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options
In this case, the lambda always returns exactly the same relationship, so there won't be any difference.
Lambda notation is commonly used to pass arguments to scope:
scope :before, lambda {|date| where.created_at < date}
Which one can be used like:
Model.before(1.day.ago)
It is naturally impossible to write this without a lambda.
source to share