Zack C. wrote:
On 11/17/06, Bryan E. [email protected] wrote:
I agree with Tom that defining a unique key in your DB and letting the
I think validates_uniqueness_of does have a “valid” place. It lets
you keep your code DRY and works in 99.999% of the cases. It only
fails in the very rare case where another insert occurs after one
thread (or mongrel process) has checked for uniqueness. In that very
rare case the db’s unique index would catch it and the database would
stay valid. The only side effect is that the app would render an
error page to the user. I’m willing to bet that this would likely
never happen until a site got really big, and in even then it would
have to be the perfect storm.
I agree with you that it would be a rare occurrance for a duplicate
value to be inserted into the DB after ActiveRecord does the uniqueness
check and before it actually saves your record.
However, it is possible. As well, your DB already does a duplicate key
check on insert/update (assuming that you defined a unique key on the
DB), so the uniqueness check done by the validation is redundant
database I/O and can’t be guaranteed to be accurate. In terms of
functionality and performance, using the validation actually seems to me
to be detrimental to an application, rather than beneficial.
Evaluating the validation on a more subjective criterion, I don’t
believe that using validates_uniqueness_of provides any DRYness to my
application code that can’t be achieved by extending ActiveRecord::Base
to handle a duplicate key error returned from the DB. Given that
validates_uniqueness_of needs to be defined multiple times in your
application code (once for each unique key), I think that defining a
generic duplicate key error handler in ActiveRecord::Base is actually a
more DRY approach, but I suppose that it is a matter of personal taste.
From my perspective, the application-side validations’ prime purpose is
to provide “fast” model validation by avoiding DB I/O. If an
application-side validation needs to perform redundant DB I/O in order
to validate an object, I can’t see the advantage of using it, especially
if it can’t even guarantee model validity.
This is just my opinion, and I respect yours as well.