Rails 计算小计和总计的方法
上下文:我有 2 个模型订单和项目。
我想根据 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 view render <%= number_to_currency(@order.total_price) %>
Context: I have 2 models Order and Item.
I want to calculate Item subtotal based on item.quantity * item.price
For now this is done in the view (but not the appropriate place).
<%= number_to_currency(item.quantity * item.price) %>
I also need to calculate the Order total but I'm stuck. I don't have any column for that.
What's the best approach? Use the model? Helper or Observer?
For now I managed to have subtotal working through Order helper
def item_subtotal(item)
item_subtotal = item.quantity * item.price
end
Working Solution:
Item model
def subtotal
price * quantity
end
In View render <%= item.subtotal %>
Order model
def total_price
total_price = items.inject(0) { |sum, p| sum + p.subtotal }
end
Order#show view render <%= number_to_currency(@order.total_price) %>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在您的 Item 模型上,您可以添加一个小计方法:
假设您的 Order 模型与 Item 具有 has_many 关系,您可以
映射
集合以获取 Order 模型上的价格列表:因为您'在 Rails 环境中运行时,您可以使用 activesupport
sum
方法来获取订单模型的总计:或者如果您更喜欢将它们放在一起:
那么您可以使用项目的小计和订单的总计在你看来。
编辑:视图可能如下所示:
On your Item model you could add a subtotal method:
Assuming that you're Order model as a has_many relationship with Item you could
map
the collection to get a list of prices on the Order model:Because you're running in a Rails environment you can use the activesupport
sum
method to get the total on an Order model:Or if you prefer putting it all together:
Then you can use the subtotal on Item and total on Order in your views.
Edit: The view could look like this:
由于它是模型的功能(您想要计算自引用的项目的某些内容),因此更合适的位置是模型本身,以便您可以轻松使用
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
,对于总计,您可以通过以下方式计算:
total_price = @order.items.to_a.sum { |item|总计 = item.product.price*item.quantity }
我认为这对您有用。
You can Show the item_subtotal by using
and for grand total you can calculate it by
total_price = @order.items.to_a.sum { |item| total = item.product.price*item.quantity }
I think this will work for you.