I am working on a rails app and have been getting the following error very often:
Mysql2::Error: Duplicate entry '3022093-2000000028003-visited' for key 'unique_user_place_relationship'
While I've narrowed the source of the problem down to the following lines:
begin
up = UserPlace.new(user_place_params)
up.skip_logging
up.save!
rescue ActiveRecord::RecordNotUnique => e
Rails.logger.warn(e)
end
In my table, I have the following indices:
key_name seq_in_index column_name
unique_user_place_relationship 1 user_id
unique_user_place_relationship 2 place_id
unique_user_place_relationship 3 relationship
Is the problem that I don't have a validate_uniqueness_of
user_id, place_id and relationship in my user_place.rb
?
From my understanding, ActiveRecord:RecordNotUnique
should catch this error since the transaction does not meet the index constraints at the db level.
The doc says:
Using this validation method in conjunction with
ActiveRecord::Validations#save
does not guarantee the absence of duplicate record insertions, becauseuniqueness
checks on the application level are inherently prone to race conditions. For example, suppose that two users try to post a Comment at the same time, and a Comment’s title must be unique. At the database-level, the actions performed by these users could be interleaved in the following manner...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With