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
has_no_table
column :name, :string
column :email, :string
column :phone_number, :string
column :message, :string
validates_presence_of :name, :email, :message
end
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.
Click
Follow me on twitter 
2 comments: