コンテキスト: Order と Item の 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 ビュー レンダー<%= number_to_currency(@order.total_price) %>