Community for developers to learn, share their programming knowledge. Register!
Views and Templating with ERB

Displaying Data from the Controller in Ruby on Rails


Welcome to our training article on displaying data from the controller in Ruby on Rails! In this piece, we will explore how to effectively pass data from your Rails controllers to views, leveraging the power of Embedded Ruby (ERB) to render dynamic content. This knowledge is essential for intermediate and professional developers looking to enhance their applications' functionality and user experience.

Passing Data to Views from Controllers

In Ruby on Rails, the MVC (Model-View-Controller) architecture is fundamental to how data flows through an application. The controller acts as the intermediary between the model and view, processing incoming requests, retrieving data, and ultimately rendering the view.

To pass data to views, you typically use instance variables. These variables are prefixed with an @ symbol and are accessible in the corresponding view template. For example, consider the following simple controller action:

class ProductsController < ApplicationController
  def index
    @products = Product.all
  end
end

In this example, the index action retrieves all products from the database and assigns them to the instance variable @products. This variable can then be accessed in the corresponding view, index.html.erb, allowing you to display a list of products dynamically.

It’s important to note that Rails uses conventions to determine which view to render. By default, the view file name will match the action name (in this case, index). This convention simplifies the development process by reducing the need for additional configuration.

Using Instance Variables to Access Data

Instance variables are crucial for sharing data between controllers and views in Ruby on Rails. Once you set an instance variable in the controller, it is available in the view for rendering.

Let’s take a closer look at how you can utilize instance variables to display data in a view template. Continuing with our products example, here’s how the view might look:

<h1>Products Listing</h1>

<% @products.each do |product| %>
  <div class="product">
    <h2><%= product.name %></h2>
    <p><%= product.description %></p>
    <p>Price: <%= number_to_currency(product.price) %></p>
  </div>
<% end %>

In this code snippet, we use ERB tags (<% %> and <%= %>) to control the flow of the template. The <%= %> tag outputs the result of the Ruby expression to the view, while <% %> is used for Ruby code that does not need to be displayed directly.

This separation allows for clear and organized templates while keeping your logic within the controller. Moreover, Rails provides helper methods like number_to_currency, which format data appropriately, enhancing the user interface.

Rendering Data in HTML with ERB

ERB (Embedded Ruby) is a powerful templating system that allows you to embed Ruby code within your HTML. This capability is essential for dynamically generating content based on the data passed from controllers.

Let’s delve deeper into some advanced rendering techniques using ERB. Consider adding conditional logic in your views to manage how data is displayed based on specific criteria. For example:

<h1>Products Listing</h1>

<% if @products.any? %>
  <% @products.each do |product| %>
    <div class="product">
      <h2><%= product.name %></h2>
      <p><%= product.description %></p>
      <p>Price: <%= number_to_currency(product.price) %></p>
    </div>
  <% end %>
<% else %>
  <p>No products available at the moment.</p>
<% end %>

In this example, we added a conditional check using if @products.any? to determine whether there are products to display. If not, a message informs the user that no products are currently available. This enhances user experience by providing meaningful feedback based on the application state.

Another useful feature of ERB is partials. Partials allow you to extract reusable pieces of view code into separate files. This practice promotes DRY (Don't Repeat Yourself) principles and keeps your views clean and maintainable. For instance, you could create a _product.html.erb partial for rendering individual products:

<!-- _product.html.erb -->
<div class="product">
  <h2><%= product.name %></h2>
  <p><%= product.description %></p>
  <p>Price: <%= number_to_currency(product.price) %></p>
</div>

You can then render this partial within your main view:

<h1>Products Listing</h1>

<% if @products.any? %>
  <% @products.each do |product| %>
    <%= render partial: 'product', locals: { product: product } %>
  <% end %>
<% else %>
  <p>No products available at the moment.</p>
<% end %>

By passing the product object to the partial via locals, you maintain a clean separation of concerns while taking advantage of reusable components in your views.

Summary

In conclusion, effectively displaying data from the controller in Ruby on Rails is crucial for creating dynamic and engaging applications. By leveraging instance variables, utilizing ERB for templating, and employing techniques like conditionals and partials, you can create well-structured views that enhance user experience.

Understanding how to pass and render data appropriately allows developers to build robust applications that respond to user interactions seamlessly. As you continue to develop your skills in Ruby on Rails, mastering these techniques will undoubtedly set you on a path toward creating more sophisticated and user-friendly applications. For further information and best practices, consider referring to the official Ruby on Rails guides that provide in-depth coverage of these topics and more.

Last Update: 31 Dec, 2024

Topics:
Ruby on Rails