Using Partials with Ruby on Rails

Ruby Template can be refactored into multiple templates which are also called partials. These templates then can be brought together by calling on each other via render method in Ruby.

For example, a good candidate for partial pages is a form with the list of items under it for seeing what was added by the user via this form. We can separate out form portion from item’s listing portion into two and present item’s listing grid as partial in Ruby. Alternatively, we can set up two partials, one for the form and another for item’s grid.

Let’s do that in practical code sample and call our first partial as _item_form.html.erb. Please note that all partials in Rails start with underscore sign in front of the file name.

<%= form_tag :action=>’new’ do -%>
 Item: <%=text_field ‘item’, ‘value’ %>
<%=submit_tag “Submit”%>
<% end -%>

Now we can simply include this partial into our main template in the following manner

<%= render :partial => ‘item_form’%>

_item_form.html.erb does not have to be included with the file name or underscores. Rails framework is smart enough to figure out what partial needs to be referenced. In addition, partial inherits all instance variable supplied by the controller of the main template which acts as a parent to this partial.

We can set up our item’s grid as partial as well. Let’s make it and call it _grid_item.html.erb

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

We can now add two partials into our main template which acts as a parent to both partials.

<h1>My Template</h1>
<ul>
<% @list.each do |item| %>
  <%= render partial: ‘grid_item’, list_item: item %>
<% end %>
</ul>
<%= render partial: ‘item_form’ %>

Important to note, partials don’t have access to local variables and if you want to include local variables you many need to pass it over to your partials via :locals. You can also pass an object to partials via object keyword as follow:

<%=render partial: ‘item_form’, object: @list%>

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…