views:

26

answers:

2

I have a validate_uniqueness_of :field inside my ActiveRecord model. When i do a single create/update it works nicely but i have to do some large batch creation from csv files inside a Transaction When i am in the transaction the validate_uniqueness_of does not detect the error and the model is saved!

A: 

validates_uniqueness_of is subject to race conditions, and you still need to have the appropriate unique constraints on your database. You are describing this situation. The link provides a few solutions.

Jarrett Meyer
i am already using the :unique => true in for the field that should be unique but to no luck inside the transaction (it works if i do a simple sql insert in command line)
PanosJee
+2  A: 

Could it be that the non-unique values are created during the transaction?

The validate methods check before the transaction and then all values are still not present in the table and thus unique.

Edit: Create a index with the unique property turned on for your field and the transaction will fail and thus preventing the addition of non-unique elements. To do some you should add something this in your migration file

add_index("tablename", "fieldname", { :name => "fieldname_index", :unique => true })

Edit 2: A transaction like this will will give something like a "ActiveRecord::StatementInvalid: Mysql::Error: Duplicate entry '123' for key 1: <sql statement here>" error.

Table.transaction do
  i1 = Table.new
  i1.fieldname = "123"
  i1.save
  i2 = Table.new
  i2.fieldname = "123"
  i2.save
end
Veger
it still does not work
PanosJee
what kind of database are you using. I just tried to add same values to a unique field using a transaction and I got an error (using MYSQL)
Veger
5.1 when i do plain insert in the db shell mysql gives the error as expected
PanosJee