CRUDのRouting 設定とHelperメソッド
いろいろとひっかかてしまうので、
Rails3 のCRUDのRouting 設定と、その設定によって生成されるHelperメソッドの関連について整理してみました。
sites という コントローラーを例にしています。
Routingの定義
routes.rb で (ActionDispatch::Routing::Mapper::Resources の) resources メソッドによって、URLとそれを処理するコントローラー、アクションの対応づけが生成されます。
Hoge::Application.routes.draw do resources :sites .. end
この設定後、rake routes を実行すると、以下のように、URL及びHTTPメソッド(GET/POST/PUT/DELETE)と、それを処理するコントローラー/アクションのRouting設定ができていることが確認できます。
$cd <application path> $rake routes sites GET /sites(.:format) {:action=>"index", :controller=>"sites"} POST /sites(.:format) {:action=>"create", :controller=>"sites"} new_site GET /sites/new(.:format) {:action=>"new", :controller=>"sites"} edit_site GET /sites/:id/edit(.:format) {:action=>"edit", :controller=>"sites"} site GET /sites/:id(.:format) {:action=>"show", :controller=>"sites"} PUT /sites/:id(.:format) {:action=>"update", :controller=>"sites"} DELETE /sites/:id(.:format) {:action=>"destroy", :controller=>"sites"}
create(新規作成)の場合は、HTTPメソッドが'POST', update(変更)の場合は'PUT'、destroy(削除)の場合は'DELETE'となるようマッピングされます。
生成されるHelper
上記のようにルーティングの定義を行うと以下のメソッドが自動的に生成されます。
site_path(site, options)
/sites/
new_sites_path(options)
/sites/
edit_site_path(site,options)
/sites/edit/
sites_path(options)
/sites というURLパスを返す。optionsには、ハッシュでリクエストパラメーターでわたすキーと値を指定。
viewでのリンク出力でのHelperの使い方
edit や destroy のリンクを作る場合の例は、以下のようになります。
editリンクの場合
link_to 'edit' ,edit_site_path(site, :page => 1) => <a href="/sites/4/edit?page=1">edit</a>
destroyリンクの場合。/sites/ のパスを、Httpメソッドを'DELETE'にしてのリクエストになります。
link_to 'destroy', site_path(site, :page => 1), :confirm => 'Are you sure?', :method => :delete => <a href="/sites/1?page=1" data-confirm="Are you sure?" data-method="delete" rel="nofollow">destroy</a>
indexの一覧ページ。
link_to 'index', sites_path => <a href="/sites">index</a>
form でのつかわれかた
form_for Helper メソッドで、以下のように、モデルレコードを引数に指定してやると、update または、create のための form が出力されます。
<%= form_for(@site) do |f| %> .. <% end %>
update が生成される場合
edit action で form_forが使われた場合、site_path メソッドが内部的に呼び出されて、updateのためのformを出力されます。以下のように、urlが/sites/
<form accept-charset="UTF-8" action="/sites/1" class="edit_site" id="edit_site_1" method="post">
create が生成される場合
new action で form_forが使われた場合、sites_path メソッドが内部的に呼び出されて、createのためのformを出力されます。以下のように、urlが/sites で Httpメソッドが'POST'となるformとなります。
<form accept-charset="UTF-8" action="/sites" class="new_site" id="new_site" method="post"
とりあえず、以上、標準的、単純な場合の使いかたについて。
あと、URLパターンなどが、違う場合(CRUDでない場合、レコードのid以外をurlのパターンに含む場合など)に、うまくLinkやFormがつくれるやりかたもかんがえないと..