Search code examples
ruby-on-railsdatabasehtml-tableextractbelongs-to

Getting info to insert from a belongs_to relationship


I've got orders, which have many line items, and line items which belong to products. I'm trying to extract the product title, but it's not appearing in the output. I'm getting the line_item info fine. They are all linked in the line_items table, which has both order_id and product_id fields. I'm pretty new to rails, please can someone help me figure out where I'm going wrong?

<% @order.line_items.each do |line_item| %>
    <tr>
        <% line_item.product do |product| %>
        <td><%= product.title %></td>
<% end %>
        <td><%= number_to_currency(line_item.price) %></td>
        <td><%= line_item.quantity %></td>
        <td><%= number_to_currency((line_item.price*line_item.quantity))%></td>
</tr>
    <% end %>

Solution

  • Try:

    <% @order.line_items.each do |line_item| %>
        <tr>
            <td><%= line_item.product.title %></td>
            <td><%= number_to_currency(line_item.price) %></td>
            <td><%= line_item.quantity %></td>
            <td><%= number_to_currency((line_item.price*line_item.quantity))%></td>
        </tr>
    <% end %>