Skip to content

Instantly share code, notes, and snippets.

@adamcaron
Last active August 29, 2015 14:27
Show Gist options
  • Save adamcaron/a88b4bc9ea1d3a7920f3 to your computer and use it in GitHub Desktop.
Save adamcaron/a88b4bc9ea1d3a7920f3 to your computer and use it in GitHub Desktop.
How params are nested depending on `form_for` and `form_tag`

reference project: form_playground/app/views/new.html.erb

form_for

form_for is useful for POST requests because it stores the params in a hash related to the object, @article.

form_for(@article) do |f|
  <%= f.label :title %>
  <%= f.text_field :title %>
  <%= f.label :body %>
  <%= f.text_area :body %>
  <%= f.submit %>
<% end %>

Stores the params as such...

{"utf8"=>"✓", "authenticity_token"=>"fakK14NsrmSL6DjhdOJNmisjlSGw6w7MTh20jjNPAEBJwCIRjNlsO3iHKnDxi0yLaqfx0tQas7PMi6+TIneP+A==", 
"article"=>{"title"=>"sweet tile", "body"=>"a descripasf "}, 
"commit"=>"Create Article", "controller"=>"articles", "action"=>"create"}

form_for nests the data in an article hash within params so we can access the article data from the params hash ... params[:article] and store it in the database with Article.create(params[:article])

form_tag

doesn't nest the params ...

form_tag articles_path do
  <%= label_tag :title %>
  <%= text_field_tag :title %>
  <%= label_tag :body %>
  <%= text_area_tag :body %>
  <%= submit_tag "Create Article" %>
<% end %>

...

{"utf8"=>"✓",
 "authenticity_token"=>"ZuxLDHoWJRRdim4iO4IyRiqCeICWmY0JJ7qRNbztDcFShWPKdaPnS67lfLO+6zNXawYcc/JoMHalLIoordWCeQ==",
 "title"=>"Some Title",
 "body"=>"The best article body ever.",
 "commit"=>"Create Article"}

form_tag may be useful when we don't need to store the data in an object. For instance, we may simply need to run a calculation on the data, or perhaps useful for a search field where we take the search term and pass it to a search algorythm.

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