0

I discovered that this validation still works

validates :name, presence: true, if: (spa) -> { spa.name_required && other_name.blank? }

This has a lambda with an argument, but the argument isn't used for the other_name check

I found that when I removed the argument to the lambda it still works

validates :name, presence: true, if: -> { name_required && other_name.blank? }

The documentation says we should be creating procs, see https://guides.rubyonrails.org/active_record_validations.html#using-a-symbol-with-if-and-unless

I think this works because a lambda is a closure inside the object it's defined so the object's methods are available.

Question is, why does the Active Record documentation say use a proc with an argument? Is using a lambda like this wrong in some way?

Ghoti
  • 2,388
  • 1
  • 18
  • 22
  • A lambda is bound to its context so the implicit `self` is the same as the outer context where it was defined. In this case `self` is the model instance. I think this is just a case of the documentation being old or poorly written as it does not really matter if you use a proc or lambda as long as you [understand the differences](https://stackoverflow.com/questions/1740046/whats-the-difference-between-a-proc-and-a-lambda-in-ruby). – max Nov 19 '18 at 17:36
  • I think so too, max, but using a lambda is much less clumsy looking :) – Ghoti Nov 20 '18 at 14:52

0 Answers0