Forms

The <form> . . </form> tag in HTML along with the form’s various input elements such textradioselect, etc. help you to create HTML forms.

For example, a basic form to accept user input for a new book record, written in plain HTML would be like this:

<form action="/books" method="post"><label for="title">Title:</label><input type="text" name="title" id="title"><label for="author">Author:</label><input type="text" name="author" id="author"><label for="price">Price:</label><input type="number" name="price" id="price"><input type="submit" value="Create Book"></form>

Include this form element in new.html.erb script and visit http://localhost:3000/books/new in the browser to display the form −

Ruby on Rails Forms

If you provide a pure HTML form in a Rails application, it raises the following issues:

  • You must manually set action and method attributes.
  • No automatic field population as the values are lost if the form fails validation – especially if the form is used for update action.
  • You must manually handle CSRF protection.

Rails Form Helpers

Rails provides various form helpers to be used along with other helpers that generate the form elements like input types. These helpers when used instead of raw HTML forms has several advantages, making development faster, cleaner, and more maintainable.

Following form helpers are available:

  • form_with
  • form_tag
  • form_for

The form_with Helper

The form_with helper is the recommended approach to render model-backed forms (linked to a database record).

When called without arguments, it creates an HTML <form> tag with the value of the method attribute set to post and the value of the action attribute set to the current page.

For example, assuming the current page is a home page at /home, the generated HTML will look like this:

<%= form_with do|form|%>
  Put Form elements here
<% end %>

The corresponding HTMLscript will look like the following:

<!--BEGIN app/views/books/new.html.erb --><form action="/books" accept-charset="UTF-8" method="post"><input type="hidden" name="authenticity_token" 
   value="XolEv4UeO6RkT0yLuhmBKvYcPANvmW4Fj1CP07wvb2Bd4-WqCvoPt_R2Zo055uQTzM-FURYNLMibkcSbiGm5pg" autocomplete="off" />PutForm elements here
</form><!--END app/views/books/index.html.erb -->

Note that the form contains a hidden input element, authenticity_token, required for POST and PUT form submissions so as to prevent cross-site request forgery (CSRF) attacks. You can thus see how the form helpers automatically enable the security feature.

The most preferred approach is to create a model-backed form y passing the model object as a parameter to form_with helper:

<%= form_with model:@bookdo|f|%>
   Put various form elements here
<% end %>

Instead of the raw HTML form elements, you can use Rails helpers to render elements such as text fields, radio buttons, etc.

The label Helper

The label helper renders a HTML label.

<%= form_with model: @book do |f| %>
  <%= f.label :title%>

This is equivalent to the HTML label element:

<label for=" title">Title</label>

The text_field Helper

The text_field helper renders a text input element, equivalent to <input type= “text”>

<%= form_with model: @user do |f| %>
  <%= f.text_field :author%>
<% end %>

The corresponding HTML code would be −

<input type="text" name="author" id="author">

The text_area Helper

The text_area helper generates a textarea element. Example:

<%= form_with model: @user do |f| %>
  <%= f.textarea :detail%>
<% end %>

The radio_button Helper

It’s the Rails helper for <input type= “radio”>. For example:

<%= f.radio_button :format,"Gender"%>

The check_box Helper

The check_box helper is used to render a check box, as done by <input type=”checkbox”>.  For example:

<%= f.check_box :available%>

The submit Helper

The submit helper outputs an <input type= “submit”> button that submits the form. Example:

<%= f.submit "Create Book"%>

Its equivalent HTML would be:

<input type="submit" value="Create Book">

We shall use these helpers to build a form that is used to enter book data.

<%= form_with(model: @book, local: true) do |f| %>
   <div class="mb-3"><%= f.label :title, class: "form-label" %>
  &lt;%= f.text_field :title,class:"form-control", placeholder:"Enter book title"%&gt;
</div><div class="mb-3"><%= f.label :author, class: "form-label" %>
  &lt;%= f.text_field :author,class:"form-control", placeholder:"Enter author's name"%&gt;
</div><div class="mb-3"><%= f.label :price, class: "form-label" %>
  &lt;%= f.number_field :price,class:"form-control", step:"0.01", placeholder:"Enter book price"%&gt;
</div><div class="d-grid"><%= f.submit "Create Book",class:"btn btn-primary"%> </div><%end%>

The browser display in response to http://localhost:3000/books/new URL is:

The submit Helper

The form_tag Helper

The form_tag helper also renders the HTML tag, but it is not linked to any ActiveRecord model. While the form_with helper uses the model object such as @book, the form_tag uses a URL path. You also must define the form submission method (POST/PUT) manually. The forms built with form_tag are generally used for setting search criteria or filters.

The helpers for rendering form elements like text field are suffixed with _tag. For example, the text_field_tag helper generates text type input field.

The following code renders a serach form with the use of form_tag helper

<%= form_tag search_books_path, method: :get do %>
  <label>Search:</label>
  <%= text_field_tag :query, params[:query]%>

  <%= submit_tag "Search" %><%end%>

The browser display in response to http://localhost:3000/books/new URL is:

The form_tag Helper

The form_tag Helper

The form_tag helper also renders the HTML tag, but it is not linked to any ActiveRecord model. While the form_with helper uses the model object such as @book, the form_tag uses a URL path. You also must define the form submission method (POST/PUT) manually. The forms built with form_tag are generally used for setting search criteria or filters.

The helpers for rendering form elements like text field are suffixed with _tag. For example, the text_field_tag helper generates text type input field.

The following code renders a serach form with the use of form_tag helper

<%= form_tag search_books_path, method: :get do %>
  <label>Search:</label>
  <%= text_field_tag :query, params[:query]%>

  <%= submit_tag "Search" %><%end%>

The form_for Helper

The form_for helper has now been deprecated since Rails 5 version, however, you can still use it. Here is an example:

<%= form_for @book do |f| %>
  <%= f.text_field :title%>
  <%= f.text_field :author %><%= f.number_field :price %>
  <%= f.submit "Save Book"%>
<% end %>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *