Problems Rescuing ActiveRecord :: RecordNotUnique

I am trying to create a table that will act as a batch synchronization queue with a third-party service.

The following method should speak for itself; but in order to be clear, its purpose is to add a new updated object (polymorphic relation) with status: :queuedto the table delayed_syncs.

There is a unique constraint for polymorphic relationships + status( updatable_id, updatable_type, status), which should trigger updates objects that are already in line with :queued statusto fail here and hit the rescue unit.

The problem that I see is that whenever the SELECTgenerated one fires , find_bythis whole method fails with:

ActiveRecord :: StatementInvalid

error.

The information I found around this offers ROLLBACKor RELEASE SAVEPOINTafter unsuccessful INSERT, but I'm not sure how to do it here.

The above method:

def self.enqueue(updatable:, action:)
  DelayedSync.create(updatable: updatable, status: :queued, action: action)
rescue ActiveRecord::RecordNotUnique
  queued_update = DelayedSync.find_by(updatable: updatable, status: :queued, action: :sync_update)
  if action == :sync_delete && queued_update.present?
    queued_update.sync_delete!
  else
    Rails.logger.debug "#{updatable.class.name} #{updatable.id} already queued for sync, skipping."
  end
end
+4
source share
2 answers

, , after_save. Rails after_save after_destroy , . ActiveRecord::RecordNotUnique, , Postgres, . after_commit, , after_save after_destroy on: [:create, :destroy], ( ) .

, - : http://markdaggett.com/blog/2011/12/01/transactions-in-rails/

0

, , ActiveRecord " ".

:

ActiveRecord::Base.transaction do
  DelayedSync.create!(updatable: updatable, status: :queued, action: action)
end

rescue .

, , .

+1

All Articles