LoginSignup
3

More than 5 years have passed since last update.

Activerecord配列@hogesの特定カラム合計を、インスタンス変数として動的に生成したい

Last updated at Posted at 2013-10-19

医療費総額と一部負担金の総額算出したいという状況で
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]にカラム名をシンボルで追加するだけで合計インスタンスが動的に量産できます。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3