Topic: Reverse table rendering

The problem here is building a table where the columns represent a user object and each row is a different attribute. Basically a reverse table rendering.  The more attributes I have to display the more times I have to cycle through the users object to build the new row of information. Is there a way to build this table in one for loop?

<h2>User information displayed in reverse table</h2>
<table>
    <tr>
        <th>&nbsp;</th>
        <% for user in @users %>   
            <th><%=h user.id %></th>
        <% end %>
    </tr>
    <tr>
        <td class="label">First Name</td>
        <% for user in @users %>   
            <td><%=h user.first_name %></td>
        <% end %>
    </tr>
    <tr>
        <td class="label">Last Name</td>
        <% for user in @users %>   
            <td><%=h user.last_name %></td>
        <% end %>
    </tr>   
    <tr>
        <td class="label">Age</td>
        <% for user in @users %>   
            <td><%=h user.age %></td>
        <% end %>
    </tr>   
    <tr>
        <td class="label">Birth Date</td>
        <% for user in @users %>   
            <td><%=h user.birth_date %></td>
        <% end %>
    </tr>   
</table>

Re: Reverse table rendering

perhaps you may try it this way:

<%- [:first_name, :last_name, :age, :birth_date].each do |attribute| -%>
    <tr>
    <td class="label"><%= attribute %></td>
    <%- @users.each do |user| -%>
    <td><%=h user.send(attribute) %></td>
    <%- end -%>
    </tr>
<%- end -%>

greetz

Re: Reverse table rendering

Thanks! That worked great.  I guess extending this question the actual text that came out in the label cell for the attribute names was first_name, last_name, birth_date and age.  Is there anyway to change the display name of the attribute like First Name, Last Name, Birth Date and Age?

Re: Reverse table rendering

look at api.rubyonrails.org and search for "humanize".

greetz

Re: Reverse table rendering

I actually did already look for that but it doesn't completely solve my problem.  The code was simply an example but in my application has attributes that can not be humanized.  For example if attributes were named "fname", "lname", "bdate"..etc

Also.. is there any clean way to get the first row.. which will be an attribute as well to be a header row using th rather than td like in the example?

Last edited by agn507 (2008-06-21 14:55:01)