New lambda literal syntax for activerecord callbacks

I wonder if this is possible?

after_create -> { some_method_from_model }, if: :should_be_executed?

The syntax is fine, but will Proc be called / executed or just created?

+4
source share
2 answers

If you want to call a method on a model, the best approach would be to pass the model as an argument to your lambda, and then use it to call the desired method, for example:

after_create -> (model) { model.some_method }, if: :execution_condition_satisfied?

This is because the value selfinside the lambda is not a model, but a Proc object, and without an explicit receiver, Ruby is trying to call the method in self.

Ruby some_model_method Proc. , , -.

, ;)

+14

. if .

after_create :some_method

def some_method
  if condition_satisfied
    #do the stuff
  end
end
+1

Source: https://habr.com/ru/post/1528102/


All Articles