Reputation: 1274
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
Upvotes: 1
Views: 1399
Reputation: 1138
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.
Upvotes: 3