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

今日はちょっとだけ。acts_as_listプラグインを使って分類を並べ替えられるようにします。

プラグンのインストール

script/plugin install acts_as_list

テーブルの変更

acts_as_pluginに必要なposition列をテーブルcategoriesに追加します。

script/generate migration add_position_to_categories

で、マイグレーション用ファイルを作成して、以下のように編集します。

class AddPositionToCategories < ActiveRecord::Migration
  def self.up
    add_column :categories, :position, :integer
  end

  def self.down
    remove_column :categories, :position
  end
end

マイグレーションを実行します。

rake db:migrate

モデルの変更

Categoryクラスを以下のように変更します。

class Category < ActiveRecord::Base
  validates_presence_of :name
  
  has_many :entries
  
  acts_as_list # 追加
end

今回は単純にソートしていますが、":scope=>"でソートの範囲を指定することができます。

ビューとコントローラの変更

ビューに分類の並べ替えのためのリンクを追加し、コントローラに変更処理を追加します。
app/views/categories/index.html.erbに以下の内容を追加します。

  ...(略)
	<td><%= link_to('↑', :action => 'move_higher', :id => category) unless category.first?%></td>
	<td><%= link_to('↓', :action => 'move_lower', :id => category) unless category.last?%></td>
  ...(略)

app/controllers/category_controller_rbに以下の内容を追加します。

class CategoriesController < ApplicationController

  def index
    @categories = Category.find(:all, :order => "position") # :order=>を追加

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @categories }
    end
  end
  
  def move_higher # 追加
    Category.find(params[:id]).move_higher
    redirect_to :action => 'index'
  end

  def move_lower  # 追加
    Category.find(params[:id]).move_lower
    redirect_to :action => 'index'
  end  
  ..(省略)
end

確認

サーバを再起動して、内容を確認します。

矢印を押すと並び替えができます。すごい簡単でした。
すでにDBにデータが登録されていると、positionの値が正しくないので、うまく動作しないかもしれません。