Chantal
Chantal Software developer focused on personal development not only as a coder but as a human being.

Rendering Data with Partials in Rails

Rendering Data with Partials in Rails

Since I learned rails I have been iterating over data in my views like this

    # assuming you have a controller and proper routes and data. 
    <% @apartments.each do |apartment| %>
    <%= apartment.unit_number %>
    <% end %>

Today while I was building an app I was in the mood to try something different and the result was baffling. It turns out rendering data with partials is super simple. Let’s say you have an apartments directory with the proper data available to you.

1.- Place the code you need in your index.html.erb file. I’m rendering apartments information inside a table and notice inside the <tbody> tags. I’m calling a partial called @apartments this variable is available for us to use thanks to our controller.

    # views/apartments/index.html.erb
    <h2>All Apartments from <%= @property.name %></h2>


    <div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
        <table class="table table-striped table-hover">
            <thead>
            <tr>
            <th>
                Unit Number
            </th>
            <th>
                Beds
            </th>
            <th>
                Baths
            </th>
            <th>
                Unit Location
            </th>
            <th>
                Garage
            </th>
            <th>
                Garage Number
            </th>
            <th>
                Renovation type
            </th>
            <th>
                Floor Plan
            </th>
            </tr>
            </thead>
            <tbody>
            <%= render @apartments %>
            </tbody>
        </table>
        </div>
    </div>
    </div>

2.- inside your apartments directory create your partial.

    # views/apartments/_apartment.html.erb
    <tr>
    <td><%= apartment.unit_number %></td>
    <td><%= apartment.beds %></td>
    <td><%= apartment.baths %></td>
    <td><%= apartment.unit_location %></td>
    <td><%= apartment.garage %></td>
    <td><%= apartment.garage_number %></td>
    <td><%= apartment.renovation_type %></td>
    <td><%= apartment.floor_plan %></td>
    </tr>

notice no iteration is required, but you have to use the naming conventions otherwise it will not work.

This is a short post I learned this today and my hope is for to be useful to somebody else.

comments powered by Disqus