4

上下文:我有 2 个模型 Order 和 Item。

我想根据 item.quantity * item.price 计算项目小计现在这是在视图中完成的(但不是在适当的地方)。

<%= number_to_currency(item.quantity * item.price) %>

我还需要计算订单总数,但我被卡住了。我没有任何专栏。最好的方法是什么?使用模型?助手还是观察者?

现在我设法通过订单助手进行小计工作

def item_subtotal(item)
  item_subtotal = item.quantity * item.price
end

工作解决方案:

物品型号

def subtotal
  price * quantity
end

在视图中渲染<%= item.subtotal %>

订购型号

def total_price
  total_price = items.inject(0) { |sum, p| sum + p.subtotal }
end

Order#show 视图渲染<%= number_to_currency(@order.total_price) %>

4

3 回答 3

7

在您的 Item 模型上,您可以添加一个小计方法:

def subtotal
  quantity * price
end

假设您将 Order 模型作为与 Item 的 has_many 关系,您可以map收集集合以获取 Order 模型上的价格列表:

def subtotals
  items.map do |i| i.subtotal end
end

因为您在 Rails 环境中运行,所以可以使用 activesupportsum方法获取 Order 模型的总数:

def total
  subtotals.sum
end

或者,如果您更喜欢将它们放在一起:

def total
  items.map do |i| i.subtotal end.sum
end

然后,您可以在视图中使用 Item 的小计和 Order 的总计。

编辑:视图可能如下所示:

<% for item in @order.items %> <%= item.price %><br/><% end %>
<%= @order.total %>
于 2011-10-16T03:53:56.637 回答
0

Since it is a functionality of the model (you want to calculate something of the item that is self-referential), the more appropriate location is the model itself, so that you can easily use

item.subtotal
于 2011-10-16T02:53:51.427 回答
0

您可以使用显示 item_subtotal

对于总计,您可以通过以下方式计算

total_price = @order.items.to_a.sum { |item| 总计 = item.product.price*item.quantity }

我认为这对你有用。

于 2015-07-24T07:04:36.417 回答