DEV Community

Brittany
Brittany

Posted on

Day 36 - #100DaysofCode - Rails form_for versus form_tag

Below is my understanding of form_for versus the form_tag

form_tag

  • form_tag creates a form.
  • form_tag can be used to create form without a model object by passing a URL to submit the form.
  • form_tag is used when we have to create a form without any model object providing URL endpoint to submit the form.

Below is an example on how to use a form_tag :

<%= form_tag("/todos") do %>
  <%= label_tag('todo[title]', "Title") %>
  <%= text_field_tag('todo[title]') %>

  <%= label_tag('todo[content]', "Content") %>
  <%= text_field_tag('todo[content]') %>

  <%= submit_tag "Create Todo" %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

This will build a form and auto generate the following HTML:

<form accept-charset="UTF-8" action="/todos" method="POST">
  <label for="todo_title">Title</label>
  <input id="todo_title" name="todo[title]" type="text">
  <label for="todo_content">Content</label>
  <input id="todo_content" name="todo[content]" type="text">
  <input name="commit" type="submit" value="Create Todo">
</form>
Enter fullscreen mode Exit fullscreen mode

form_for

  • form_for is used when we have to create a form for a model object.
  • form_for is a bit easier to use for creating forms for a model object because it yields a FormBuilder object that lets you create form elements that correspond to attributes in the model. Meaning that it figures out what url it needs to use and what http method it must go to generate form for a new/existing model object.
  • form_for is a ruby method into which a Ruby object is passed. This means that a form that utilizes form_for is directly connected with an Active Record model

Below is an example on how to use a form_for helper :

<%= form_for(@todo) do |t| %>
  <%= t.label :title %>
  <%= t.text_field :title %>
  <%= t.label :content %>
  <%= t.text_field :content %>
  <%= t.submit %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

The form_for above will auto generate the following HTML:

<form accept-charset="UTF-8" action="/todos" method="post">
  <label for="todo_title">Title</label>
  <input id="todo_title" name="todo[title]" type="text" />
  <label for="todo_content">Content</label>
  <input id="todo_content" name="todo[content]" type="text" />
  <input name="commit" type="submit" value="Create" />
</form>
Enter fullscreen mode Exit fullscreen mode

How I interpret it is, if you know and have a model for an object you should be using the form_for method, otherwise you need to generate your own form by using the form_tag method.

Resources:

rails-form-with-alternative-to-form-for-and-form-tag
The Flatiron School Curriculum

Song of the day:

Oldest comments (0)