Whenever I create, update, or destroy a model I need to send a notification to a front end app. When sending the message, I need to know if the record is a newly created record OR if the record has been deleted. To avoid duplication I'd prefer to handle all of this in a single ActiveRecord lifecycle hook (i.e. before_save, after_save, after_commit, etc).
My issue seems to be that in the before_save
callback, destroyed?
will return false when I am destroying the object, but if I use after_commit
then new_record?
will return false even if I just created the object.
Is there a way I can reliably identify:
- if a record was or will be destroyed
and
- if a record is or was a new record
at a single point in the objects lifecycle?
before_save
is triggered right before you create or update a record (new one or existing one) with save, so why are you expectingdestroyed?
to be true inside the callback ? Same withafter_commit
, once you create, update, or destroy the record can't be anew_record?
. – limekindestroyed?
ornew_record?
). – AndrewHafter_commit :new_record, on: :create
(record created) enough ? You can build or send the message inside the methodnew_record
(no need to check if it's newly created) and you can add one for each of:create
and:update
. More here : api.rubyonrails.org/classes/ActiveRecord/Transactions/… – limekin