Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql2::Error: Duplicate entry for key -- ActiveRecord::RecordNotUnique not catching error?

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.

like image 210
Huy Avatar asked Mar 06 '13 19:03

Huy


1 Answers

The doc says:

Using this validation method in conjunction with ActiveRecord::Validations#save does not guarantee the absence of duplicate record insertions, because uniqueness 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...

like image 87
Pioz Avatar answered Oct 12 '22 23:10

Pioz