Skip to content

Instantly share code, notes, and snippets.

@zacksheppard
Created July 10, 2014 12:39
Show Gist options
  • Save zacksheppard/fda30fa8fa54f6c4bf5f to your computer and use it in GitHub Desktop.
Save zacksheppard/fda30fa8fa54f6c4bf5f to your computer and use it in GitHub Desktop.
Rails form_for example

From: http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html

To create a new person you typically set up a new instance of Person in the PeopleController#new action, @person, and in the view template pass that object to form_for:

<%= form_for @person do |f| %>
  <%= f.label :first_name %>:
  <%= f.text_field :first_name %><br />

  <%= f.label :last_name %>:
  <%= f.text_field :last_name %><br />

  <%= f.submit %>
<% end %>

The HTML generated for this would be (modulus formatting):

<form action="/people" class="new_person" id="new_person" method="post">
  <div style="display:none">
    <input name="authenticity_token" type="hidden" value="NrOp5bsjoLRuK8IW5+dQEYjKGUJDe7TQoZVvq95Wteg=" />
  </div>
  <label for="person_first_name">First name</label>:
  <input id="person_first_name" name="person[first_name]" type="text" /><br />

  <label for="person_last_name">Last name</label>:
  <input id="person_last_name" name="person[last_name]" type="text" /><br />

  <input name="commit" type="submit" value="Create Person" />
</form>

As you see, the HTML reflects knowledge about the resource in several spots, like the path the form should be submitted to, or the names of the input fields.

In particular, thanks to the conventions followed in the generated field names, the controller gets a nested hash params[:person] with the person attributes set in the form. That hash is ready to be passed to Person.create:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment