Things To Remember While Working With Uniqueness In Rails

validation_uniqueness_of does not guarantee uniqueness. Interesting write-up by Yogesh about things to remember while working with uniqueness in Rails.

Happy Coding !!!

♦ The Problem

Consider the following relation where poll is having many options and each option of the poll must be having a unique description,

Now, when trying to create a poll with its options using nested attributes, uniqueness validation is not getting applied due to race condition.

> poll = Poll.new(options_attributes: [ { description: 'test' }, { description: 'test' } ])
> poll.save
=> true
>
> poll.options
=> [#<Option id: 1, description: "test">, #<Option id: 2, description: "test">]

♦ Why it is occurring ?

There is a section in UniquenessValidator class, which mentions that the ActiveRecord::Validations#save does not guarantee the prevention of duplicates because, uniqueness checks are performed at application level which are prone to race condition when creating/updating records at the same time. Also, while saving the records, UniquenessValidator is checking uniqueness against the records which are in database only, but not for the records which are…

View original post 128 more words

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.