davidb
davidb

Reputation: 8954

has_and_belongs_to_many and unique index on association table generates "Duplicate entry" fail

I have several has_and_belongs_to_many associations and I also used the uniq option in associations to avoid MySQL errors in relation with duplicate keys. My associations are like this:

has_and_belongs_to_many :people, :uniq => true

The index I added is a divided primary key I added using:

add_index :table_name, [:key_1, :key_2], :unique => true

on both sides of the assocation. But when I try to associate an object twice my application throws the Mysql2::Error: Duplicate entry '1-9' for key... error which is generated by MySQL. Is there a smart way to handle this problem?

I have thought about several possible solutions but the arent smart. I thought about changing the INSERT query manually by using the :insert_sql option but that would be a lot of work dong this for 20 association tables. Is there a better way to deal with this?

Upvotes: 3

Views: 1154

Answers (1)

Frederick Cheung
Frederick Cheung

Reputation: 84114

The uniq option doesn't try very hard to prevent duplicates from being added - if the association is loaded it will check whether the object is already in there but it won't load the association just to check.

The easiest thing is probably to rescue ActiveRecord::RecordNonUnique and deal with it appropriately - no matter how careful your ruby level checks are there's always going to be a chance of a race condition that gets caught by the database

Upvotes: 3

Related Questions