Re: Another validation question

François Beausoleil
Mon, 05 Sep 2005 04:19:20 -0000

Hi !

Dewey Howell said the following on 2005-09-03 22:23:
> First user correctly adds "Cindy Tompkins" to the database
>
> Second user attempts to add "Tompkins Cindy" because he mixes up
the
> last_name and first_name fields on the form and didn''t notice that
the
> person was already added to the database.
>
> -----------------------
>
> This scenario happens frequently because some people naturally think
> "Last Name first" and others "First Name first" and
there will be
> inconsistencies despite clear instructions on the page.
>
> How do I use validate to prevent this?

Use a validation helper method:
class Patient < ActiveRecord::Base
   validate :first_last_uniqueness

private
   # Checks that first, last and last, first are unique
   def first_last_uniqueness()
     self.errors.add(:first, ''First and last must be unique'')
if
         self.find(:first,
               :conditions => [''last = ? and first = ?'',
                   self.last, self.first])
     self.errors.add(:first, ''First and last must be unique'')
if
     self.find(:first,
               :conditions => [''first = ? and last = ?'',
                   self.last, self.first])
   end
end

WARNING: Untested code

In fact, you can write any method, and you add to the errors collection
to do your validation.

Hope that helps !
François