zero-divisor
zero-divisor

Reputation: 610

Ruby/Rails, ActiveRecord uniqueness validation and activerecord-import gem

In my RESTful API I have a uniqueness validation for some database-column "X" within my ActiveRecord class and I'm using the activerecord-import gem for bulk-saving data. My app should reject requests in both of the following cases:

  1. Reject a new object if there exists a record in the db that has the same "X" value
  2. Reject bulk-saving two objects that have the same "X" value

It seems like (1.) is working fine, but (2.) is not. Is this to be expected (maybe because the ActiveRecord uniqueness validation is performed "outside" the db), and if yes, is there simple way to handle this issue other than validating by hand before importing the new data?

Upvotes: 3

Views: 2339

Answers (1)

abhishek
abhishek

Reputation: 1008

The activerecord-import gem enforces validations by default, but perhaps handles uniqueness validation differently. If the database supports it, there is a on_duplicate_key_update which will update another column if it finds duplicate keys. More about this on the wiki. MySql supports it.

So you can either have a flag type column that is updated via on_duplicate_key_update whenever there are attempts to save duplicates. Or you have to do this one validation by hand

Edit The answer may not be correct, please refer to OP's comments for details.

Upvotes: 1

Related Questions