简体   繁体   中英

Rails uniqueness validation does not seem to be working

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 ?

  1. Try to restart a server or reload console after adding code to any file in the project.

  2. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM