Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 680
zero-divisor Avatar asked Jan 25 '26 13:01

zero-divisor


1 Answers

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.

like image 51
abhishek Avatar answered Jan 28 '26 06:01

abhishek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!