おこづかい帳アプリを作る(4)

Railsの勉強の続きです。今日やること。

  • 一覧は今月分のみ表示するようにする
  • 前月分、来月分に移動できるようにする
  • その月の支出の合計を表示するようにする

とりあえず、表示対象の年月をURLのパラメータで"2009-08"ので渡すようにします。EntriesController#indexを以下のように変更しました。

  def index
    if params[:yearmonth]
      date = params[:yearmonth].split('-')
      @target_date = Date.new(date[0].to_i, date[1].to_i)
    else
      @target_date = Date.today # パラメータが未指定の場合は今月
    end
    
    from = @target_date.strftime("%Y-%m-01") # 期間指定開始日
    to = (@target_date >> 1).strftime("%Y-%m-01") # 期間指定終了日
    
    @entries = Entry.paginate :all, :page => params[:page],
                 :per_page => 10,
                 :conditions => ["occurred_at >= ? AND occurred_at < ?", from, to],
                 :order => 'occurred_at ASC'

    # 合計の取得
    @sum = Entry.sum :amount, :conditions => ["occurred_at >= ? AND occurred_at < ?", from, to]

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @entries }
    end
  end

パラメータで表示対象年月が指定されていない場合には今月を対象にしています。ついでに、createとupdateが完了したらデータを保存した月の一覧に遷移するようにするため、redirect_toを以下の様にしてみました。

        format.html { redirect_to :actin => 'index', :yearmonth => @entry.occurred_at.strftime("%Y-%m")}

次に、index.html.erbにページ移動用のリンクと合計表示を追加しました。

<div id="date">
  <span><%= link_to 'prev', :action => 'index', :yearmonth => (@target_date << 1).strftime("%Y-%m")%></span>	
  <span><%=h @target_date.strftime "%Y年%m月" %></span>
  <span><%= link_to 'next', :action => 'index', :yearmonth => (@target_date >> 1).strftime("%Y-%m")%></span>	
</div>
	
<div id="sum">
  <span>Sum:</span>
  <span><%= amount_format(@sum) %></span>
</div>

amount_formatは前回金額の表示フォーマットを指定していた部分をヘルパーメソッドに切り出しました。

今日学んだこと

  • Controllerにパラメータを渡す
  • ActiveRecordで集計関数を使う

表示する年月をパラメータで渡すより"entries/2008/08"みたいな方がRESTfulっぽいですね。合計を表示するために、sumを使ってみたのですが簡単でよいですね。