Search code examples
ruby-on-railsviewpartial

Render table in partial Rails 4.0


Could someone help me render a table view partial? Basically, I have a Link model with two attributes: Description and URL. My Link model is a nested resource of my Opportunity model. Therefore when I click "show" on an opportunity, I want it to show the Opportunity then show all the links that belong to that opportunity. I want the links to be rendered into a table with columns labeled "Description" and "URL". My current code looks like this:

views/opportunities:

<%= render @opportunity %>
<h3>Links</h3>
<div id = "links">
  <%= render @opportunity.links %>
</div>

views/links/_link

<%= div_for link do %>

    <p>Description:<%= link.description %></p>
    <p>URL: <%= link.link_url %></p>
    <span class='actions'>
            <%= link_to 'Delete', [@opportunity, link], :confirm => 'Are you sure?',
                :method => :delete %>
    </span>
<% end %>

Solution

  • You're going to want...

    <%= render @opportunity %>
    <h3>Links</h3>
    <table id = "links">
      <thead><tr>
        <th>Description</th>
        <th>URL</th>
      </tr></thead>
    
      <tbody>
        <%= render @opportunity.links %>
      </tbody>
    </table>
    

    And then...

    <tr>
      <td><%= link.description %></td>
      <td><%= link.link_url %></td>
      <td><span class='actions'>
            <%= link_to 'Delete', [@opportunity, link], :confirm => 'Are you sure?',
                :method => :delete %>
      </span></td>
    </tr>
    

    I'm a little unclear on how you're using the span in the partial, so I left it as a separate column in the table.

    I hope that helps.