script/console で URL がどんな params に認識されるかを確かめる
まず config/routes.rb が次のような内容になっているものとします。
ActionController::Routing::Routes.draw do |map| map.connect 'date/:year/:month/:day', :controller => 'blog', :action => 'by_date', :month => nil, :day => nil map.connect ':controller/:action/:id' end
script/console 中で app.get に URL を渡すとその URL にアクセスしたときの処理を行ってくれます。その後に puts app.controller.assigns["url"] を実行することでどんな params になったのかを確認することができます。
$ script/console Loading development environment. >> Rails::VERSION::STRING => "1.1.6" >> app.get "http://localhost/date/2006/09/22" => 302 >> puts app.controller.assigns["url"] http://, localhost, /date/2006/09/22, blog, by_date, {"month"=>"09", "action"=>"by_date", "controller"=>"blog", "day"=>"22", "year"=>"2006"} => nil >> app.get "http://localhost/date/2006/09" => 302 >> puts app.controller.assigns["url"] http://, localhost, /date/2006/09, blog, by_date, {"month"=>"09", "action"=>"by_date", "controller"=>"blog", "year"=>"2006"} => nil >> app.get "http://localhost/date/2006" => 302 >> puts app.controller.assigns["url"] http://, localhost, /date/2006, blog, by_date, {"action"=>"by_date", "controller"=>"blog", "year"=>"2006"} => nil >> app.get "http://localhost/date" => 404 >> puts app.controller.assigns["url"] http://, localhost, /date, , , {} => nil
逆に params を URL に変換するのには app.url_for を使います。
>> app.url_for(:controller => "/blog", :action => "by_date", :year => 1999) => "http://localhost/date/1999" >> app.url_for(:controller => "/blog", :action => "by_date", :year => 1999, :month => 9, :day => 22) => "http://localhost/date/1999/9/22"
ちなみに app.get の呼び出し時には config/routes.rb が自動的に reload されますが、app.url_for の時には reload されません。こういうときには ActionController::Routing::Routes.reload を呼び出せば強制的に reload させることが出来ます。
>> # ここで ↑ で示した map.connect を消した >> app.url_for(:controller => "/blog", :action => "by_date", :year => 1999, :month => 9, :day => 22) => "http://localhost/date/1999/9/22" # 変わってない >> ActionController::Routing::Routes.reload => [] >> app.url_for(:controller => "/blog", :action => "by_date", :year => 1999, :month => 9, :day => 22) => "http://localhost/blog/by_date?day=22&month=9&year=1999" # :controller/:action/:id が使われた