Jun 29, 2009

Validating form_tag in ActiveRecord

Activerecord valiations are seriously cool. If you just want to validate something in your form it's as easy as specifying the validation in your model and letting Rails take care of the rest. But what if you want to validate a form_tag? Generally, we use form_tag when there's no model associated with our form. Without the model we can't use Activerecord validations! Well, it turns out there's an elegant solution to the problem thanks to the Tableless Activerecord gem.

Now normally I'm pretty hesitant about adding a gem dependency to my application. These things tend to break between major rails upgrades and if the plugin developer isn't beholden to thousands of users it could be a while before you see a fix. In the end, if you're desperate, you could end up maintaining code you hadn't intended to.

The Tableless Activerecord gem is pretty straight forward though. Even though it hasn't been updated in a year, it seems to work fine with Rails 2.3.2. Usage is also pretty simple. To validate a contact form without a user model, just create a file called something like contact_messenger.rb and populate with the fields in your contact form and the validates you want:

class ContactMessage < ActiveRecord::Base


column :name, :string
column :email, :string
column :phone_number, :string
column :message, :string

validates_presence_of :name, :email, :message


In the above example, our contact form has fields for name, email, phone number, and message, but we're only requiring name, email, message. All other validations will work here as well so, for example, if you want to require the phone number be of a particular length you can do that as well.

Full instructions for using the gem/plugin can be found on Kenneth Kalmer's website.


  1. This looks interesting. I have a question that revolves around form_tag in general. I do happen to have a model and I'm trying to validate a date that returns 'invalid date' when a user submits an empty/nil date.

    I've tried using validation_timeless plugin which allows you to validate_date :date :format etc... but validation checks are not reaching the form_tag.

    It leads me to believe that all form_tags can't be associated with a model and therefore might have to use something like this. But does this only affect validation checks?

    For instance, what if the form_tag is making a call to xyz model but you want to use validation in zyx model with this plugin. How does the form_tag work.

    Any brief examples you can give showing this?



  2. I've been using a module I picked up somewhere along the line that I think works the same way. Just throw this in your lib folder and include it in any models. Less scary than a gem dependency: