[Rails] validations first impressions

Dick Davies rasputnik at hellooperator.net
Tue Feb 1 12:50:08 GMT 2005


I got coaxed into using these after a few pointers on IRC last night,
having used db constraints up to that point.

Still feels a bit wrong to be doing the dbs job for it, but I have to
say I've got a lot more flexibility this way (regex > LIKE )...

It also means I can just assert ( foo.save) rather that catching db
adapter specific Exceptions, which must help portability
at the end of the day.

One little gotcha I found was I'd set

validates_prescence_of : username

in the model. When I ran the unit tests, I got an SQLException
(because I still had the UNIQUE constraint in the db).

Shouldn't the above have thrown some kind of 'NoMethodError'
(In case you missed it, the method is validates_presence_of...) ?

If it wasn't for my trusty buddy sqlite I'd have crap in the db now
(admittedly because I can't type worth a damn, but still)...

Also is there a neater way to say 'if the field is non-nil, validate its format'
than:

# fails when email is nil
#validates_format_of :email, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/

  protected
  def validate
    errors.add("email", "has invalid format") unless (
      email.nil? || email =~ /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/
    )
  end

Yes, I know. I want the moon on a stick... :)


  [
    PS: Started doing TDD with Rails last night and it's a breeze
    ( I've got a nicely debugged model and haven't even generated a controller yet).

    Thanks very much to all concerned for setting up the test framework, the rakefiles,
    etc (especially the console, it's my favourite power tool).
 ]

-- 
'common sense is what tells you that the world is flat.'
		-- Principia Discordia
Rasputin :: Jack of All Trades - Master of Nuns


More information about the Rails mailing list