Topic: Model validation

Several of my models use this snippet for validation. It is a way to do validates_inclusion_of without so many database calls. See here.

  validates_each [ :user_id, :license_id ] do | record, attrib, value |
      attrib.to_s.titleize.camelize.gsub(/ /, '').constantize.find(value)
    rescue ActiveRecord::ActiveRecordError
      record.errors.add attrib, 'must be present and valid'

The items in the validates_each array vary, but the rest of the code is the same. I'm guessing I can move it off to a method, but where do I put it to be usable by all the models? I'm not sure where common code goes for those.

Re: Model validation

Create a file in your lib folder and slap it in there. Afterwards be sure to include the file at the top of your model and of course restart your server to see results.

Of course, if this is something you find yourself using in more than one project, you could always make it into a plugin.

Re: Model validation

Works great...thanks.