You are here: Home Solidarrow Ruby on Rails Solidarrow Cheatsheets

* Form Helpers Cheatsheet

Create forms, check boxes, radio buttons, select lists and more using Rails' built-in form helpers.

Parsing form data

When a form is submitted to a Rails application, the parameters are automatically translated by Rails into the params object which is accessible as a hash structure.

  • Key/value pairs of your form's input fields are stored simply as key/value pairs in the params hash, such as the id which is extracted by routing from the URL:

/customers/1

id=1

{ :id => "1" }

/customers/1?color=red

id=1&color=red

{ :id => "1", :color => "red" }

  • Square brackets [] are used to build more complex, nested structures:

text_field :user, :name

user[name]=David

{ :user => { :name => "David" }

text_field "user[address]", :city

user[address][city]=London

{ :user => { :address => { :city => "London" }}}

text_field "user[address]", :street

user[address][street]=Road

{ :user => { :address => { :street => "Road" }}}

  • Using empty square brackets [] after the name of a model object, such as address[], will insert the id of the record you are editing into the input field, useful for editing multiple records on one form:

text_field "address[]", :country

address[4][country]=England

{ :address => { 4 => { :country => "England" }}}

text_field "address[]", :town

address[4][town]=London

{ :address => { 4 => { :town => "London" }}}

  • If the record is new and has no id, then upon submitting the form, Rails will convert the fields into an array of hashes in order of appearance:
    text_field "address[]", :country 
    text_field "address[]", :town
    text_field "address[]", :country
    text_field "address[]", :town

    { :address => [
        { :country => "England", :town => "London" },
        { :country => "Australia", :town => "Sydney" }
      ]
    }
 

 

> RELATED ARTICLE

* Quickly debugging form helpers

Sometimes you want to quickly see the output of helper methods, and constantly clicking refresh in your browser then viewing the page source can be tiresome. Instead, use the Rails console to check helpers are doing what you want them to. > More