I have this validation rules below for my product model, and while testing the rules, I found that the uniqueness: true for :title actually does nothing.
validates( :title, presence: {message: ' must be given'}, uniqueness: true )
For instance, if I create two instances with same title like so,
a = Product.new title: 'title', description: 'hello!!', user: User.find(39)
a.save
id | title | description | price | created_at | updated_at | user_id |
+-----+-------+-------------+-------+--------------------+-------------+
162 | title | hello!! | 0.0 | 2018-... | 2018-02... | 39 |
b = Product.new title: 'title', description: 'hahah', user: User.find(39)
b.save
id | title | description | price | created_at | updated_at | user_id |
+-----+-------+-------------+-------+--------------------+-------------+
163 | title | hahah | 0.0 | 2018-... | 2018-02-2... | 39 |
I don't understand why the uniqueness doesn't work at all ?
Try to restart a server or reload console after adding code to any file in the project.
Uniqueness validation is not trusted in 100% events. TO be sure that some field is unique add a unique index in your database. It's caused by that uniq validation checks that the attribute's value is unique just before save, so if two different database connections create two records with the same value it will not raise error.