2
votes

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:

  1. if a record was or will be destroyed

and

  1. if a record is or was a new record

at a single point in the objects lifecycle?

1
before_save is triggered right before you create or update a record (new one or existing one) with save, so why are you expecting destroyed? to be true inside the callback ? Same with after_commit, once you create, update, or destroy the record can't be a new_record?.limekin
I understand the reasoning (and wouldn't expect anything different in these callbacks) I'm just wondering if there is a way to achieve what I'm trying to do (perhaps with methods other than destroyed? or new_record?).AndrewH
Isn't something like after_commit :new_record, on: :create(record created) enough ? You can build or send the message inside the method new_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
@limekin that will work! I didn't know you could specify action for a callback.AndrewH

1 Answers

1
votes

Use after_commit :

after_commit :new_record, on: :create
after_commit :update_record, on: :update
after_commit :destroy_record, on: destroy

private
  def new_record
    # Send or build message here.
  end
  def update_record
    # Send or build message here.
  end
  def destroy_record
    # Send or build message here.
  end