Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 730
conspirisi Avatar asked Dec 15 '09 22:12

conspirisi


2 Answers

You will need FormHelper methods:

Say you want a simple test action that submits to do_test action:

A simple view for test action (posts/test.html.erb):

<% form_tag '/posts/do_test' do %>
    <%=label_tag 'name' %>
    <%=text_field_tag 'name'%>

    <%=label_tag 'phone' %>
    <%=text_field_tag 'phone'%>

    <div><%= submit_tag 'Save' %></div>
<% end -%>

In the posts controller:

def test
end

def do_test
  name = params[:name]
  phone = params[:phone]
  # do whatever you want...
end

Also you need to add these 2 actions to the routes in config/routes.rb

map.resources :posts, :collection=>{:test => :get, :do_test => :post}
like image 59
khelll Avatar answered Sep 28 '22 09:09

khelll


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.

like image 32
Luke Francl Avatar answered Sep 28 '22 09:09

Luke Francl