医療費総額と一部負担金の総額算出したいという状況で
hogesテーブルには
t.integer "price_total"
t.integer "price_charged"
が含まれます。
class HogesController < ApplicationController
def index
@hoges = Hoge.find(:all)
[:price_total,:price_charged].each do |summable|
sum=0
@magics.each do |magic|
sum=sum+magic[summable]
end
instance_variable_set('@' + summable.to_s + '_sum',sum)
end
ーーーー以下省略
使い方
app/views/hoges/index.html.erb
<table>
<tr>
<th>請求額:<br>総額¥<%=@price_total_sum%></th>
<th>負担金:<br>総額¥<%=@price_charged_sum%></th>
合計したい、合計可能なカラムがあれば [:price_total,:price_charged]にカラム名をシンボルで追加するだけで合計インスタンスが動的に量産できます。