If you create a class to represent your object (Let's call it ContactInfo
) you can define methods on that class, then use them using the standard Rails form builder helpers.
class ContactInfo
attr_accessor :name, :company, :email, :phone, :comments
def initialize(hsh = {})
hsh.each do |key, value|
self.send(:"#{key}=", value)
end
end
end
And in your form:
<h2>Contact Us</h2>
<% form_for(@contact_info, :url => path_for_your_controller_that_handles_this, :html => {:method => :post}) do |f| %>
<%= f.label :name %>
<%= f.text_field :name %>
...
<% end %>
So far, who cares right?
However, add in the validatable gem, and you've got a real reason to do this! Now you can have validation messages just like a real model.
Check out my completed ContactInfo class:
class ContactInfo
include Validatable
attr_accessor :name, :company, :email, :phone, :comments
validates_presence_of :name
validates_presence_of :email
validates_presence_of :phone
def initialize(hsh = {})
hsh.each do |key, value|
self.send(:"#{key}=", value)
end
end
end
I like this because you can write your controller much same way as an ActiveRecord object and not have to muss it up with a lot of logic for when you need to re-display the form.
Plus, if you're using Formtastic or another custom form builder, you can use this object with it, easily keeping your existing form styles.