Ruby on Rails ActiveRecord uniqueness validation

China☆狼群 提交于 2019-12-11 10:04:14

问题


I'm pretty new to Rails and was reading some resources on the subject. And I got some questions on it. Ok, let's say we do have a model, that validates some attribute uniqueness:

class User < ActiveRecord::Base
  attr_accesible :name
  validates :name, uniqueness: true
end

So, I reasonably expect now, that I will not be able to create (or to be more precise -- save) two User instances with the same name into the database. However, this resource does insist, that it is still possible!

  • Some user signs in.
  • Clicks 'Sign in' button more than one time
  • Request 1 creates user in memory (valid)
  • Request 2 creates user in memory (valid)
  • Request 1 is successfully saved
  • Request 2 is successfully saved

And later on this source advises to add index in database to the 'name' column and make it unique.

But, if as I said it before -- validation takes place upon save procedure, then how is it possible for the 2nd request to be saved? Or I've lost something?

(the resource I was mentioning is Rails Tutorial


回答1:


The second request is fired before the first record is saved in DB, so rails verifies that there isn't a record with the name specified an allows it to save. That's why it is recommended to add an unique to the database field, to avoid these edge cases.

Or in other words, the records passes the validations in memory.



来源:https://stackoverflow.com/questions/14942608/ruby-on-rails-activerecord-uniqueness-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!