How should I write multiple condition in after_create callbacks
Asked Answered
C

3

13

I have a method in model that calls after create

after_create :generate_insurer_recovery_invoice, if: :insurance_recovery_batch?

How should I write another condition within this callback?

Cheese answered 10/3, 2016 at 7:20 Comment(1)
W
24

You can also do this for a shorter readable version

after_save :update_offices_people_count, if: -> {office_id_changed? || trashed_changed?}

P.S: -> is a shorthand version of writing lambda.

Weihs answered 23/1, 2018 at 21:42 Comment(2)
not sure if this is a version issue, but i needed to put a comma before the "if"Onestep
I do agree, right syntax is after_save :update_offices_people_count, if: -> {office_id_changed? || trashed_changed?}Trail
C
5

I think this may be usefull to you

You can achive this something like this, from the following post

Multiple conditions on callbacks

after_save :update_offices_people_count

private

def update_offices_people_count
  if office_id_changed? || trashed_changed?  
    ...
  end
end
Cottontail answered 10/3, 2016 at 7:40 Comment(2)
Have better solution with lambda after_save close_claim_for_unrecoverable, if: lambda {|di| di.unrecoverable? && di.unrecoverable_changed? }Cheese
after_save close_claim_for_unrecoverable, if: lambda {|di| di.unrecoverable? && di.unrecoverable_changed? }Cheese
R
0

Pass an Array of conditions.

The lambda or proc methods work well but you can also just pass in an Array to if, like so:

after_create :generate_insurer_recovery_invoice, if: [ :insurance_recovery_batch?, :active_insurer? ]

I'm not sure what version of Rails this was added but take a look at the Rails 7 docs here:

https://guides.rubyonrails.org/active_record_callbacks.html#multiple-callback-conditions

Ralaigh answered 18/4, 2023 at 22:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.