Rendering Collections in Rails 5

Steps

Step 1

The tasks controller index action retrieves all the tasks.

def index
  @tasks = Task.all
end

Step 2

The task view index.html.erb loops through all the tasks and displays them.

<h1> Tasks</h1>
<ul>
<% for task in @tasks %>
  <li> 
      <%= task.name %> 
  </li> 
<% end %>
</ul>

Step 3

Create a task partial _task.html.erb.

<li> 
    <%= task.name %> 
</li> 

Step 4

Let's render collection using the partial we created in the previous step. Change index.html.erb.

<h1> Tasks</h1>

<ul>
<%= render partial: 'task', collection: @tasks %>   
</ul>

Step 5

You can simplify this even further.

<h1> Tasks</h1>

<ul>
<%= render @tasks %>    
</ul>

This works, because, the name of partial is the same as the objects in the collection. If there are no tasks, the render will return nil so you can provide a default value.

<h1> Tasks</h1>

<ul>
<%= render @tasks || 'There are no tasks.' %>   
</ul>

Step 6

You can have a different name for the items you want to render in the partial by using the as: option.

<h1> Tasks</h1>

<ul>
<%= render partial: 'task', collection: @tasks, as: :todo %>    
</ul>

In the task partial, you can now use todo instead of task.

<li> 
  <%= todo.name %> 
</li> 

Step 7

You can pass a local variable by using the locals. Change the task index page.

<h1> Tasks</h1>

<ul>
<%= render partial: 'task', collection: @tasks, as: :todo, locals: {title: 'My Honey Do List'} %>   
</ul>

You can now access the title local variable in the task partial.

<li> 
  <%= todo.name %> <%= title %>
</li> 

This will render:

Get rich quick My Honey Do List
Write a book My Honey Do List
Buy a puppy My Honey Do List
Dance in the rain My Honey Do List

in the tasks index page.

Summary

In this article, you learned how to render a partial with collection instead of looping through them in the view.


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.