asahi
asahi

Reputation: 3333

Rails and html table

I'm using rails and I'm wondering if what I'm trying to do is possible with html tables. I'm iterating over an object that has many categories. Each category has one or more books and each book as a "pages" attribute. I'd like to create a table that looks like this:

**category**     **book name**     **pages**
general            book1             15
                   book2             20
                   book3             40

I believe this would correspond to one row in the table, but the last two columns obviously have multiple rows within them. I've been able to accomplish this with code that looks like:

<table>
  <thead><th>category</th><th>book name</th><th>pages</th></thead>
  <tbody>
    <% category.each do |c| %>
    <tr>
      <td><%= c.name %></td>
      <td>
        <% c.books.each do |b| %>
          <%= b.name %><br />
        <% end %>
      </td>
      <td>
        <% c.books.each do |b| %>
          <%= b.pages %><br />
        <% end %>
      </td>
    </tr>
    <% end %>
  </tbody>
</table>

As you can see, I'm iterating over the c.books twice, which seems messy. Is there a way for me to do this while iterating over c.books just once? I'd love to hear any suggestions.

Upvotes: 1

Views: 2880

Answers (1)

Don Leatham
Don Leatham

Reputation: 2704

If you don't mind having each book on its individual row in the table, you can omit the category name after the first row and get the same format you describe above. Here is the html.erb code:

<table>
  <thead><th>category</th><th>book name</th><th>pages</th></thead>
  <tbody>
    <% category.each do |c| %>
    <% first_row = true %>
    <% c.books.each do |b| %>
      <tr>
        <% if first_row == true %>
          <td> <%= c.name %> </td>
          <% first_row = false %>
        <% else %>
          <td></td>
        <% end %>
        <td> <%= b.name %> </td>
        <td> <%= b.pages %> </td>
      </tr>
    <% end %>
    <% end %>
  </tbody>
</table>

Hope this helps!

Upvotes: 1

Related Questions