|
|
|
|
|
by dwheeler
2142 days ago
|
|
I think this is pretty clearly documented:
https://guides.rubyonrails.org/active_record_validations.htm... "This [uniqueness] helper validates that the attribute's value is unique right before the object gets saved. It does not create a uniqueness constraint in the database, so it may happen that two different database connections create two records with the same value for a column that you intend to be unique. To avoid that, you must create a unique index on that column in your database." It's pretty clear from that text that if you want a unique index in a database, it has to be a uniqueness constraint in database itself. But that's true for any such system, that's not specific to Rails. In most applications there are simple isolated validations you can verify without consulting the database, and other validations that can only be validated by consulting the database (such as uniqueness). Rails can do that, as can many other frameworks. I don't think that's broken, that's how things are. |
|
Simply removing the uniqueness validation and relying exclusively on database indices would be strictly better. ActiveRecord dynamically infers from the DB schema which columns your tables have; it could also infer foreign key relationships and uniqueness guarantees and use them to generate pre-insertion “best guesses” about validity if the user wants to run those without necessarily inserting. But Rails is supposed to be an opinionated framework, and “just try to insert and we’ll let you know how that worked out for you, since we can’t make any guarantees otherwise” is a perfectly valid opinion.