Ruby On RailsのRESTについて

RESTで書かれているプロジェクトを修正する機会があったので、RESTについてちょっと調べてみました。

informationsコントローラーがあるとするとroutes.rbにこんな風に書きます。

ActionController::Routing::Routes.draw do |map|
map.resources :informations
end

そうするとそれぞれのURLが以下のようになります。

メソッド  URL     アクション   パラメーター
GET   /informations     index
GET   /informations/new   new 
POST   /informations     create 
GET   /informations/1    show     :id -> 1
GET   /informations/1/edit  edit     :id -> 1
PUT   /informations/1    update    :id -> 1
DELETE  /informations/1    destroy   :id -> 1


上記のアクションの中にないアクションを作成したい場合は
以下のように書きます。

ActionController::Routing::Routes.draw do |map|
map.resources :informations,:member => 'confirm_destroy'
end

ちなみにmemberと似ているcollectionというオプションがあるんですが、これの違いは、デフォルトのどのアクションと同じ処理かによって使い分けます。

member:show,destroy
collection:index、new、create

となります。


特定のURLを付けたい場合は、下記のように書きます。

ActionController::Routing::Routes.draw do |map|
map.resources :informations, :path_prefix => 'admin'
end

indexアクションの場合「admin/informations」のようになります。