Table of contents
1.
Introduction
2.
What are Forms?
3.
Forms in HTML
4.
Viewing What A Form Submits
5.
Railsifying Your Form
6.
Form Helpers: form_with
7.
Forms and Validation
8.
Making PATCH and DELETE Submissions
9.
Frequently Asked Questions
9.1.
Explain Rails Migration?
9.2.
What are strong parameters? Explain in brief.
9.3.
What is the difference between false and nil in Ruby.
10.
Conclusion
Last Updated: Mar 27, 2024

Working with forms - Basics in Ruby on Rails

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

Introduction

Ruby on Rails, usually called rails, is a server-side web application development framework created in the Ruby programming language. It adheres to the MVC (model-view-controller) architecture, which offers a default framework for databases, web pages, and web services. It also adheres to web standards like JSON or XML for data transmission and HTML, CSS, and JavaScript for the user interface.

This blog will teach us about HTML Forms, Railsifying those forms, Form Helpers, Forms with params and much more.

What are Forms?

Forms are an essential interface for user input in online applications. However, due to the necessity to manage form control names and their multiple characteristics, form markup may soon become laborious to develop and maintain. Rails eliminate this complexity by supplying view helpers for producing form markup. However, because these helpers have diverse use cases, developers must understand the differences between the helper methods before using them.

Forms in HTML

Forms are an essential user input interface in web applications. On the other hand, form markup may quickly become hard to build and maintain, owing to the need to handle form control names and its many features. Rails remove this complication by providing view helpers for creating form markup. However, because these aids have a wide range of applications, developers must grasp the distinctions before employing them.

<form action="/somepath" method="post"> <input type="text"> <!-- other inputs here --> <input type="submit" value="Submit This Form"> </form>

Viewing What A Form Submits

Look through the output sent to your console when you run the $ rails server to see what your forms send to your Rails app. Whenever you submit a very simple form for a user email registration, it should contain lines like:

Started POST "/user" for 127.0.0.1 at 2013-11-21 19:10:47 -0800 Processing by UsersController#create as TURBO_STREAM Parameters: {"utf8"=>"✓", "authenticity_token"=>"jJa87aK1OpXfjojryBk2Db6thv0K3bSZeYTuW8hF4Ns=", "email"=>"foo@bar.com", "commit"=>"Submit Form"}

The first line specifies the HTTP method that was utilised and the path that the form took. The second line specifies which controller and action will handle the form; the TURBO STREAM action is the default. The third line includes everything that will be crammed into the controller's params hash. In the next sections, we'll go through the contents.

Railsifying Your Form

You'll first notice that trying to construct a basic vanilla form in a Rails view won't work. You will receive an error, or your user session will be terminated (depending on your Rails version). This is because Rails, by default, safeguards you from cross-site request forgery and needs you to validate that the form was submitted from a page you developed. It creates an "authenticity token" that appears nonsense but aids Rails in matching the form with your session and the application.

So, if you want to design your form that Rails will handle, you must also give the token. Fortunately, Rails has a function called form_authenticity_token for doing so, which we'll go through in the project.

<input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>">

 

Making Forms into params

Each of these inputs is slightly different in structure, although some similarities exist. One thing to remember is the name property that may be assigned to an input tag. This is critical in Rails. When Rails constructs the params hash, the name property instructs it what to label the data you submitted in that input field.

<input type="text" name="description">

 

Consequently, your params hash will have a key named description, which you may access normally, e.g. params[: description] within your controller. That's also why some inputs, such as radio buttons (where type="radio"), employ the name property to determine which radio buttons should be grouped so that selecting one unclicks the others. Surprisingly, the name property is crucial!

Nesting data was another topic we discussed in the controller section. Instead of maintaining them all at the top level, you'll frequently wish to neatly bundle provided data into a hash. This is handy because, like with controllers, it allows you to make a one-line #create (after allowing the parameters using #need and #permit).

Form Helpers: form_with

Rails strive to make your life as simple as possible. Thus it naturally includes helper methods that automate some of the tedious elements of constructing forms. That doesn't imply you shouldn't know how to make forms in an old-fashioned manner. When utilising helpers, it's MORE necessary to grasp your form foundations because you'll need to understand what's going on behind the scenes if something happens.

 

Begin by creating a form with a helper, which accepts a block representing all of the form's inputs. It handles the CSRF security token we discussed before by automatically constructing the hidden input for it, so you don't have to. You provide parameters to tell it the route to submit (the current page is the default) and which method to utilise. Then there are tag helpers, such as text field tags, that produce the appropriate tags for you. All you need to do is define what you want the field to be called when it is submitted.

<%= form_with(URL: "/search", method: "get") do %> 
<%= label_tag(:query, "Search for:") %> 
<%= text_field_tag(:query) %> 
<%= submit_tag("Search") %>
<% end %>

 

Creates the form

 

<form accept-charset="UTF-8" action="/search" method="get"> 
<label for="query">Search for:</label> 
<input id="query" name="query" type="text" /> 
<input name="commit" type="submit" value="Search" data-disable-with="Search" /> 
</form>

 

There are a few things to note when using the form_with helper.

  1. The ID of the inputs matches the name.
  2. After submitting a form, the second line finishes with TURBO STREAM when you look at your output in your console. Turbo Drive now submits all forms by default. This implies that when the form is submitted, there is no full request cycle, and the website does not refresh. Add the relevant data property discussed in the Turbo Drive lecture to deactivate this.

Forms and Validation

What happens if your form is submitted, but the validations you set fail? What if the user's password is too short, for example? To begin with, you should have had some JavaScript validations as the first line of protection, and they should have caught that. But we'll cover that in a later course. In any case, your controller should be configured to re-render the current form.

You should probably show the problems, so the user understands what went wrong. Remember that when Rails attempts to verify an object and fails, it adds a new set of properties called errors to the object. You may view these errors by going to your object name. Errors.

`There are two useful helpers you can use to display such errors elegantly in the browser: #count and #full messages. Look at the code below:

<% if @post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> <% @post.errors.full_messages.each do |msg| %> <li><%= msg %></li> <% end %> </ul> </div> <% end %>

 

This will display a message informing the user of the number of errors, followed by a message for each fault.

The nicest thing about Rails forms helpers is that they handle problems automatically! If you use the form with model: @article in the example above, Rails will check for errors and, if any are found, it will automatically wrap a special div> element around that field with the class field with errors so you can add whatever CSS you want to make it stand out. Cool!

Making PATCH and DELETE Submissions

Because browsers only enable GET and POST queries, forms aren't meant to remove items natively. Rails provide a workaround by inserting a hidden field called the "_method" onto your form. It notifies Rails that you want to execute a PATCH (aka PUT) or DELETE request (whatever you selected) and may look something like input name=" method" type=" hidden" value=" patch">.

Rails will add this to your form if you supply an option called: method to form with, for example:

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

Frequently Asked Questions

Explain Rails Migration?

A Rails migration is a tool for modifying an application's database structure. Instead of dealing with SQL scripts, you specify database changes using a domain-specific language (DSL). Because the code is database-agnostic, you may rapidly transfer your project to a new platform. Migrations may be rolled back and maintained alongside your application source code.

What are strong parameters? Explain in brief.

Many Rails projects use Strong Parameters, also known as Strong Params, to improve the security of data submitted via forms. Developers can utilise strong parameters to regulate which parameters are accepted and used by the controller. Any unnecessary or possibly dangerous parameters will be disregarded and properly filtered out by permitting just the anticipated parameters.

What is the difference between false and nil in Ruby.

In Ruby, false is a FalseClass object representing a boolean value, whereas Nil is a NilClass object representing the lack of a value. It has a unique object id of 4.

Conclusion

This article extensively discussed HTML Forms, Railsifying those forms, Form Helpers, Forms with params and much more. We hope this blog has helped you enhance your knowledge relating to Ruby on Rails.

Check out our Ruby Vs Ruby on RailsRuby on Rails for Web Dev Projects, and All about Ruby on Rails articles. Practice makes a man perfect. To practice and improve yourself for the interviews, you can check out Top 100 SQL problemsInterview experienceCoding interview questions, and the Ultimate guide path for interviews. Do upvote our blog to help other ninjas grow. Happy Coding!

 

 

Live masterclass