Table of contents
1.
Introduction
2.
Dealing with basic forms
2.1.
Helpers for generating form elements
2.1.1.
Checkboxes 
2.1.2.
Radio Buttons 
3.
Dealing with model objects 
3.1.
Binding a form to an object 
3.2.
Relying on Record Identification
3.3.
How do forms with PATCH, PUT, or DELETE methods work?
3.4.
Using Date and Time Form Helpers
4.
PrepopulatingselectTags with Collections
5.
Nested Forms
6.
Designing your own forms
7.
Frequently Asked Questions
7.1.
What function does Active Record provide in Ruby specifically?
7.2.
What do you comprehend about the Ruby on Rails ERB?
7.3.
What have you found to be the finest aspect of Ruby on Rail so far?
8.
Conclusion
Last Updated: Mar 27, 2024
Easy

Working with Forms - advancing in Ruby on Rails

Author Shivani Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby programmers created the web application development framework known as Rails. Rails are part of Ruby. It is intended to make web application programming simpler by assuming that all developers have the prerequisites for getting started. Compared to many other languages and frameworks, Ruby on rails enables you to write less code while doing more. Additionally, seasoned Ruby on Rails developers claims that it increases the enjoyment of creating web applications.

Before moving forward, there are a few misconceptions that need to be cleared up. Form objects are frequently used to simplify the controller and the model, which isn't wrong but doesn't do them justice given the crucial role they play.

Reduced decoupling between the controller, model (including multiple models), and view template results from moving responsibilities to the form object.

There are instances where creating a form that can handle numerous items (like model objects) at once is necessary to create a decent user experience. Users only prefer to click the submit button once, therefore you had better be able to provide them with the straightforward interface they want.

Forms are a crucial user input interface in online applications. However, due to the necessity to handle form control names and their multiple characteristics, form markup may easily become onerous to develop and maintain. Ruby on Rails eliminates this complexity by offering view helpers that provide form markup. Developers must first be aware of the variations between the assistance methods because these helpers have various use cases.

Dealing with basic forms

Form with is the primary form helper. This way of calling it creates a form tag that when filled out will POST to the current page. For instance, the resulting HTML will seem as follows, assuming the current page is the home page:

<form accept-charset="UTF-8" action="/" method="post">
  <input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
  Form contents
</form>


You'll see that there is an input element with a hidden type in the HTML. This input is crucial because, without it, non-GET forms cannot be submitted correctly. Cross-site request forgery protection is a security feature of Ruby on Rails, and form helpers create the hidden input element with the name authenticity token for each non-GET form (provided that this security feature is enabled)

Helpers for generating form elements

Numerous assistance methods are available in the form builder object returned by form for creating form components including text fields, checkboxes, and radio buttons. The name of the input is always the first parameter for these methods. The name will be sent to the params in the controller along with the form data when it is submitted, along with the value that the user-supplied for that field. You might, for instance, use params[: query] in the controller to retrieve the value of the field if the form has <%= form.text_field :query %>. Ruby on Rails has naming standards for inputs that enable the submission of parameters with non-scalar values, such as arrays or hashes, which will also be used.

Checkboxes 

Checkboxes are form controls that allow the user to enable or disable a set of choices.

<input type="checkbox" id="coding_ninjas" name="coding_ninjas" value="1" />
<label for="pet_dog">I own a course</label>
<input type="checkbox" id="coding_ninjast" name="coding_ninjas" value="1" />
<label for="pet_cat">I own a course</label>


The name of the input is the first parameter to check box. The input value is the second argument. When the checkbox is selected, this value will be present in the parameters as well as the form's data.

Radio Buttons 

Although they resemble checkboxes, radio buttons are controls that specify a group of options that are mutually exclusive (the user can only select one):

<input type="radio" id="DSA" name="course1" value="subject1" />
<label for="age_child">I am course DSA</label>
<input type="radio" id="SQL" name="course2" value="subject2" />
<label for="age_adult">I am course SQL</label>


The input value is the second parameter for the radio button, just like it is for the check box. The user can only choose one of these two radio buttons because they both have the same name (age), and params[: age] will either include "child" or "adult."

Dealing with model objects 

Binding a form to an object 

We can associate the form builder object with a model object using the form with function: model argument. As a result, the form's fields will be filled with data from that model object and will be scoped to that model object.

<%= form_with model: @article do |form| %>
  <%= form.text_field :title %>
  <%= form.text_area :body, size: "60x10" %>
  <%= form.submit %>
<% end %>

Relying on Record Identification

Since the Article model is directly accessible to application users, you should designate it a resource in accordance with standard practices for building with Ruby on Rails:

resources:articles


Calls to form when working with RESTful resources can become much simpler if you rely on record identification. Simply send the model object to Ruby on Rails, and it will take care of the model name and the rest. The results of the long and short styles are the same in both cases:

## Creating a new article
# long-style:
form_with(model: @article, url: articles_path)
# short-style:
form_with(model: @article)
## Editing an existing article
# long-style:
form_with(model: @article, url: article_path(@article), method: "patch")
# short-style:
form_with(model: @article)

How do forms with PATCH, PUT, or DELETE methods work?

Because the Rails framework favors RESTful architecture, you'll be making a lot of "PATCH," "PUT," and "DELETE" calls as you develop your applications (besides "GET" and "POST"). However, when it comes to submitting forms, the majority of browsers only offer "GET" and "POST" methods.

In order to get around this problem, Rails uses a hidden input called "_method," which is set to represent the chosen method, to emulate other methods through POST:

form_with(url: search_path, method: "patch")

Using Date and Time Form Helpers

Ruby on Rails offers substitute date and time form helpers that render basic choose boxes if you don't want to use HTML5 date and time inputs. Each temporal component is represented by a pick box by these tools (e.g. year, month, day, etc). If we have a @person model object, for instance:

@person = Person.new(joining_date: Date.new(2002, 08, 05))

PrepopulatingselectTags with Collections

Dropdown menus can be created in Rails in a few useful methods such that data is already present when the form is loaded (otherwise, they aren't very useful).

The simplest HTML method is to construct a number of <option> tags inside of your <select> tag. If you wanted to choose a post to view from a list of them, you could easily build them in your ERB code by just iterating over some collection.

# app/views/posts/new.html.erb
  ...
  <select name="user_id">
    <%= @users.each do |user| %>
      <option value="<%= user.id %>"><%= user.name %></option>
    <% end %>
  </select>
  ...


In the resulting dropdown list, each user's name appears as an option. An attribute named user id will be assigned to your #create action.

However, Rails offers various less verbose alternatives to accomplish the same task, such as by combining the #select tag and #options for select helpers. While the #options for select provide the array of options required by the #select tag, the #select tag will generate the surrounding tag.

Nested Forms

You want to have a form that creates one of your User objects (for example, for your application that mimics Amazon.com) and also create one or more ShippingAddress objects (which a User can have many of). How can you make one form create both so that your user isn't forced to repeatedly click the "submit" buttons?
This involves several steps. Your controller, view, models, and routes are all involved. the entire MVC staff.
Here, we'll give a general outline of the procedure:

  1. In order to generate one or more ShippingAddress objects if it obtains their properties when generating a standard User, you must prepare the User model. This is accomplished by including a method with the name # that accepts nested attributes in your User model. This method accepts the name of an association, such as:
# app/models/user.rb
  class User < ActiveRecord::Base
    has_many :shipping_addresses
    accepts_nested_attributes_for :shipping_addresses
  end


2. This technique has a few novel elements. #fields for was mentioned in the class on Basic Forms, but it probably means something else to you now. It effectively describes how to create a form within a form, which makes sense given that #form really uses it in the background. In this case, we could use our relationship to produce three "sub-forms" for ShippingAddress objects, like as

<%= form_with model: @user do |f| %>
    ...
    <% 3.times do %>
      <%= f.fields_for @user.shipping_addresses.build do |sub_form| %>
        ...
        <%= sub_form.text_field :zip_code %>
        ...
      <% end %>
    <% end %>
    <%= f.submit %>
  <% end %>
 


The new shipping address objects might (and should) have also been created in the controller rather than the view; this is simply for demonstration.

Designing your own forms

Despite all the helpful helpers Rails provides, there are occasions when you just want to do something unconventional. You should first consider whether this is the simplest and most direct course of action. Build your form as soon as it passes the smell test.

Starting with the most fundamental HTML forms is frequently the simplest thing to do and is also helpful practice while learning. It will be impossible to use helpers if you don't grasp what the basic HTML is doing (and remember to include your CSRF token). After you have a firm grasp of the situation, progressively incorporate Rails helpers like #form tag and #form with.

Frequently Asked Questions

What function does Active Record provide in Ruby specifically?

Its key goal is to make sure that all validations may be taken into account promptly and that the relationship between the object and the database is preserved.

What do you comprehend about the Ruby on Rails ERB?

Users of this web application framework are provided with a program known as ERB. Actually, it is an acronym for Embedded Ruby. This should be taken into account when directly inserting Ruby-related codes into HTML files. The nicest part about this program is that users don't need to worry even when they are complicated.

What have you found to be the finest aspect of Ruby on Rail so far?

Contrary to other frameworks, it fully allows metaprogramming, allowing all codes to be created quickly and without taking into account other, more complex programs. This method is one of the finest things about Ruby since it makes large tasks easy to complete quickly.

Conclusion

To sum it up, in this article we discussed the basics of Ruby on Rails, and how to deal with basic forms. We discussed some of the Helpers for generating form elements like checkboxes, radio buttons, etc. Then we discussed how to deal with model objects like Binding a form to an object, Relying on Record Identification,  PATCH, PUT, or DELETE methods work, and Using Date and Time Form Helpers. Then we saw PrepopulatingselectTags with Collections, nested forms, and how to design your own forms. 

For more content about ruby on rails, and how to make projects with them kindly refer to all our here. We also have courses on how to master ruby on rails, kindly check them out here, and for more information, go through our course here. The major differences between ruby and ruby on rails are discussed here.  For all other information regarding ruby on rails, visit our page here.

For more content, Refer to our guided paths on Coding Ninjas Studio to upskill yourself.

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

 

Live masterclass