Monday, 15 September 2014

ruby on rails - When to and when not to use lambda for named scopes? -



ruby on rails - When to and when not to use lambda for named scopes? -

i looking understand effect of lambda on named scope:

i have 2 scopes defined on model:

scope :credits, lambda { where("comparison_ind != 'peer'")} vs scope :credits, where("comparison_ind != 'peer'")

what difference between 2 statements? comparison_ind column belonging same model.

in rails 4

always utilize lambda. sec syntax wrong in rails 4 , throw error (undefined method 'call' activerecord::relation)

# activerecord/lib/active_record/scoping/named.rb scope = all.scoping { body.call(*args) } in rails 3

scope method behaves same way in both cases - created new class method called credits. difference when given lambda, evaluates lambda every time new method called scope, while when given relation, uses has been passed.

# activerecord/lib/active_record/named_scope.rb options = scope_options.respond_to?(:call) ? scope_options.call(*args) : scope_options

in case, lambda homecoming same relation, no difference noted.

lambda notation used pass arguments scope:

scope :before, lambda {|date| where.created_at < date}

which can used like:

model.before(1.day.ago)

this naturally impossible write without lambda.

ruby-on-rails ruby

No comments:

Post a Comment