reference project: form_playground/app/views/new.html.erb
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])
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.