Views

Rails View is an ERB program that shares data with controllers through mutually accessible variables. Rails uses ERB (Embedded Ruby) as its default template engine to interpret and process .html.erb files.

If you look in the app/views directory of any Rails application, you will see one subdirectory for each of the controllers. Each of these subdirectories was created automatically when the same-named controller was created with the generate script.

Rails lets you know that you need to create the view file for each new method. Each method you define in the controller needs to have a corresponding erb file, with the same name as the action (method), to display the data that the method is collecting.

Assume that a controller is created with the following command:

rails generate controller Book

This will create the controller (app/controllers/books_controller.rb). If you define an action inside this controller:

defindexend

You need to create the view file as app/views/books/index.html.erb.

ERB (Embedded Ruby) allows you to write Ruby code inside HTML using special tags:

ERB SyntaxPurpose
<% … %>Executes Ruby code (no output)
<%= … %>Executes and outputs the result
<%# … %>Comment (ignored in output)

So, let’s create view files for all the methods we have defined in the books_controller.rb. While executing these views, simultaneously check these actions are applicable into the database or not.

Creating View File for create Action

Modify the books_controller.rb file to add following action methods:

defnew@book=Book.newend

Here, @book is an instance variable. The new action initializes a new Book and used in app/views/books/new.html.erb to build the form and enter Book details. (We shall see how to create the form).

Also define create action to handle the form submission. The form data is submitted to this action which calls save method of the book instance and pushes a flash message indicating the success.

defcreate@book=Book.new(book_params)[email protected]
  flash[:notice]="Book was successfully created."
  redirect_to @book# Redirects to show action (book details)else
  render :new, status::unprocessable_entityendend</pre>

Rails form Helpers

Rails recommends using its helpers instead of using the normal HTML elements to build the content tags and form elements. The following code in new.html.erb uses form helpers like form_with, form.label, form.text_field etc. to render a blank Book form.

<%= form_with(model: @book, local: true, html: { class: 'book-form' }) do |form| %>

  <div class="field"><%= form.label :title, class: 'form-label' %>
&lt;%= f.text_field :title,class:"form-control", placeholder:"Enter book title"%&gt;
</div><div class="field"><%= form.label :author, class: 'form-label' %>
&lt;%= f.text_field :author,class:"form-control", placeholder:"Enter author's name"%&gt;
</div><div class="field"><%= form.label :price, class: 'form-label' %>
&lt;%= f.number_field :price,class:"form-control", step:"0.01", placeholder:"Enter book price"%&gt;
</div><div class="actions"><%= form.submit CreateBook', class: 'form-submit' %>

Some of the Rails view helpers are as follows:

  • form_with − Generates a form based on a Model
  • form_tag − Creates a form without a model

Following helpers are used inside the form helper form_with, for example −

<%= form_with(model: @book, local: true) do |f| %>
  <%= f.label :title%>
  <%= f.text_field :title %><%= f.submit "Save"%>
<% end %>

Form element helpers

  • label : renders a HTML label
  • text_field : renders a text input element, equivalent to <input type= "text">
  • text_area : generates a textarea element
  • radio_button : Rails helper for <input type= "radio">
  • check_box : used to render a check box, as done by <input type="checkbox">
  • submit : outputs an <input type= "submit"> button that submits the form.

URL & Link Helpers

  • link_to : creates a hyperlink, equivalent to href
  • button_to : generates a form-based button
  • image_tag : Inserts an image, similar to img src

Make sure that the config/routes.rb file is present with following resources statement.

resources :books

Start the Rails server

rails server

Add New Book

Visit http://localhost:3000/books/new URL to display the form.

Add New Book

Enter data for a new book and click the Create Book button.

Creating View File for list of books

The index action in the BooksController stores all the objects in the Book model in @books variable.

defindex@books=Book.all
end

This will need the index.html.erb file. The book data is displayed in a HTML table. In addition to the columns title, author and price, we use link_to helper to hyperlink buttons for show, edit and delete actions are provided in each row.

We also use the flash[:notice] helper to extract the flash messages pushed by any of the earlier actions.

<div class="container"><h2 class="text-center">All Books</h2><!-- Flash Messages -->
  <% if flash[:notice] %>
&lt;p class="notice"&gt;&lt;%= flash[:notice] %&gt;&lt;/p&gt;
<% end %> <!-- Books Table --><table class="table table-bordered table-striped"><thead class="table-dark"><tr><th>ID</th><th>Title</th><th>Author</th><th>Price</th><th colspan=3>Actions</th></tr></thead><tbody>
  &lt;% @books.each do |book| %&gt;
    &lt;tr&gt;&lt;td&gt;&lt;%= book.id %&gt;&lt;/td&gt;&lt;td&gt;&lt;%= book.title %&gt;&lt;/td&gt;&lt;td&gt;&lt;%= book.author %&gt;&lt;/td&gt;&lt;td&gt;₹&lt;%= book.price %&gt;&lt;/td&gt;&lt;td&gt;
        &lt;%= link_to "Show", book_path(book), class: "btn btn-info btn-sm me-2" %&gt;
        &lt;/td&gt;&lt;td&gt;
        &lt;%= link_to "Edit", edit_book_path(book), class: "btn btn-warning btn-sm me-2" %&gt;
        &lt;/td&gt;&lt;td&gt;
        &lt;%= link_to "Delete", book_path(book), method: :delete, data: { confirm: "Are you sure?" }, class: "btn btn-danger btn-sm" %&gt;
      &lt;/td&gt;&lt;/tr&gt;
  &lt;% end %&gt;
&lt;/tbody&gt;&lt;/table&gt;&lt;!-- Button to Add New Book --&gt;
<%= link_to "Add New Book", new_book_path, class: "btn btn-primary mt-3" %> </div>

The index view displays the list of books as follows −

Creating View File for list of books

Creating View File for show Method

The show action in booksController fetches a book of the ID passed to it as the parameter

defshow@book=Book.find(params[:id])# Fetch book by IDend

The corresponding show.html.erb view template is as follows:

<div class="container"><h2 class="text-center">Book Details</h2><div class="card"><div class="card-body"><h4 class="card-title"><%= @book.title %></h4><p><strong>Author:</strong> <%= @book.author %></p><p><strong>Price:</strong> ₹<%= @book.price %></p></div></div>

  <%= link_to "Back to Books", books_path, class: "btn btn-secondary mt-3" %>
</div>

Click on the Show button of inside the desired row to display the detailed view of a book.

Creating View File for show Method

Creating View File for edit Method

Add the edit action in the BooksController to fetch the specified book object.

defedit@book=Book.find(params[:id])end

This will render the edit.html.erb view, which we shall write later.

Also, add the update action to process the data submitted by the edit template.

defupdate@book=Book.find(params[:id])[email protected](book_params)
  redirect_to @book, notice:"Book was successfully updated."else
  render :edit, status::unprocessable_entityendend</pre>

The edit.html.erb code is similar to new.html.erb, except that the fields are populated with the data of the book to be updated.

<div class="container"><h2 class="text-center">Edit Book</h2>

  <%= form_with model: @book, local: true do |form| %>
&lt;div class="form-group"&gt;
  &lt;%= form.label :title %&gt;
  &lt;%= form.text_field :title, class: "form-control" %&gt;
&lt;/div&gt;&lt;div class="form-group"&gt;
  &lt;%= form.label :author %&gt;
  &lt;%= form.text_field :author, class: "form-control" %&gt;
&lt;/div&gt;&lt;div class="form-group"&gt;
  &lt;%= form.label :price %&gt;
  &lt;%= form.number_field :price, class: "form-control" %&gt;
&lt;/div&gt;
&lt;%= form.submit "Update Book", class: "btn btn-success mt-3" %&gt;
<% end %> <%= link_to "Cancel", book_path(@book), class: "btn btn-secondary mt-3" %> </div>

While on the index page that shows the list of books, click on the edit button to update the details. Change the desired data and click on Update book button. The browser returns the list of books with a flash message “Book was successfully Updated”

Creating View File for edit Method

Finally, the delete action in the BooksController calls the destroy() method on the selected Book object and removes from the book model.

defdelete@book=Book.find(params[:id])@book.destroy
redirect_to books_path, notice:"Book was successfully deleted."end</pre>

What is Next?

Hope now you are feeling comfortable with all the operations of Rails.

The next chapter explains how to use Layouts to put your data in a better way. We will show you how to use CSS in your Rails applications.

Comments

Leave a Reply

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