This project is archived and is in readonly mode.

#5494 ✓stale
Adam Meehan

Uniqueness validator can cause error with after_initialize callback

Reported by Adam Meehan | August 30th, 2010 @ 04:59 AM

The uniqueness validator uses the exists? method as the test for a duplicate record. The exists? method calls the find_by_sql method which will instantiate any record found. However the instantiated record will only have the primary attribute method defined because it is the only column in the select.

Given that the record is actually instantiated, any after_initialize callbacks will be run. If the an attribute method other than the primary key is called, then an ActiveModel::MissingAttribute error is raised. There seems to be an exception where the attribute method is called with the self receiver. Otherwise the error will occur.

I have attached a patch which uses 'count > 0' as the duplicate record test and therefore no record is instantiated and the callbacks are not run. This should also make it a little faster when a duplicate is found.

Perhaps a wider issue is whether the exists? method needs to do anything other than a count as well.

Comments and changes to this ticket

Create your profile

Help contribute to this project by taking a few moments to create your personal profile. Create your profile »

<h2 style="font-size: 14px">Tickets have moved to Github</h2>

The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>

People watching this ticket

Attachments

Pages