Override Validations in Rails Models

We have a fairly elaborate User model set up with tons of validations, etc. The client wanted to be able to create temporary users who wouldn’t have user names, passwords, etc. I was kind of stumped as to what to do (short of straight SQL) but my friend Rob had a great suggestion that worked very well. Just override User.

So – say you have a User model:
class User < ActiveRecord::Base validates_presence_of :login end [/source] When you do a [source:ruby]User.create!(:first_name => “bob”)[/source] it’s going to throw errors at you.

So – override… like this:
class TempUser < User def should_validate?; false; end end class User < ActiveRecord::Base validates_presence_of :login, :if => :should_validate?
def should_validate?; true; end

Now you can do a [source:ruby]UserTemp.create!(:first_name => “bob”)[/source] with no errors and get all that crap data into your tables.

Thanks Rob!