Alex Rivera | Logout

How to do a non-model form in ruby on rails?

Asked 2009-12-15T22:38:39.980
22

I'm trying to make a non-model form in ruby on rails, most of the examples I can find only have one field (say a search field) or use an old way of writing a form like this An Email Form with Ruby on Rails

If anyone could show me example code of a non-model form with say two fields for the view and how I access those fields in the controller I'd be grateful.

Thanks so much.

Edit
Report

1 Answer

7

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.

answered 2009-12-15T23:12:01.960

Your Answer