audited icon indicating copy to clipboard operation
audited copied to clipboard

Accessing audit corresponding to current transaction in after_commit or after_save

Open stripedpumpkin opened this issue 5 years ago • 0 comments

Hello. Is there a way to access the audit corresponding to the current transaction in an after_commit or after_save hook?

Of course we could do the following:

class Cat
  after_commit :export_observation, on: :update

  def register_observation(latitude:, longitude:)
    update!(
      latitude: latitude,
      longitude: longitude
    )
  end

  private

  def export_observation
    CatLocationRegistry.perform_async(
      id,
      audits.last.id # Ok up to race condition
    )
  end
end

But if we have frequent updates, we expose ourselves to a race condition, as audits.last might not refer to the audit we are actually interested in (and in the example above, we might end up losing an observation).

The ideal code would look something like

  def export_observation
    CatLocationRegistry.perform_async(
      id,
      current_audit
    )
  end

Is there a similar way to access the current_audit. If not, would be it feasible to add this feature? And, in case you would like someone to write a PR, could you give pointers as how this could be done ?

Lastly, if you think this is not feasible, could elaborate on why?

Thanks for reading.

stripedpumpkin avatar Jun 30 '20 07:06 stripedpumpkin