【问题标题】:Getting info to insert from a belongs_to relationship从 belongs_to 关系中获取要插入的信息
【发布时间】:2012-06-19 07:40:45
【问题描述】:

我有订单,其中有很多订单项,订单项属于产品。我正在尝试提取产品标题,但它没有出现在输出中。我得到了 line_item 信息。它们都链接在 line_items 表中,该表同时具有 order_id 和 product_id 字段。我对rails很陌生,请有人帮我弄清楚我哪里出错了?

<% @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 %>

【问题讨论】:

    标签: ruby-on-rails database html-table extract belongs-to


    【解决方案1】:

    试试:

    <% @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 %>
    

    【讨论】:

    • 我没有意识到你可以遍历这样的关系 - 即 line_item.product.title。 - 非常感谢,已经解决了!
    猜你喜欢
    • 2018-05-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-18
    • 1970-01-01
    • 2011-06-26
    相关资源
    最近更新 更多