-
Notifications
You must be signed in to change notification settings - Fork 8
浜松rails3道場 routing編
mackato edited this page May 10, 2011
·
39 revisions
浜松Rails3道場とは、習うより慣れろ方式で、Rails3のツボを浜松のRubyist達へ伝える試みである。
- Ruby on Rails Guides: Rails Routing from the Outside In
- RailsCasts - #203 Routing in Rails 3
- Ruby on Rails Documentation
練習用のRailsプロジェクトを作る。参考環境: Ruby 1.9.2, Rails 3.0.7
% rails new routing-dojo
% bundle install
HTTPリクエスト(URL、メソッド)を受け取って、コントローラーのアクションを呼び出す仕組み。また、パスやURLを生成し文字列によるこれらのハードコードを回避することができる。
The Rails router recognizes URLs and dispatches them to a controller’s action. It can also generate paths and URLs, avoiding the need to hardcode strings in your views.(Ruby on Rails Guides)
確認用のコントローラーを生成
rails g controller catalog view
設定ファイルにrouteを追加する。
# config/routes.rb
match 'products/:id' => 'catalog#view'
Viewで使う
<% # app/views/catalog/view.html.erb %>
<%= link_to 'Product: 2', :controller => 'catalog', :action => 'view', :id => 2 %>
Controller内で呼び出す
# app/controllers/catalog_controller.rb
redirect_to :controller => 'catalog', :action => 'view', :id => 3
- サーバーを起動しブラウザで確認
- rake routes
- テスト
コントローラーのテスト
# test/functional/catalog_controller_test.rb
# assert_generates(expected_path, options, defaults={}, extras = {}, message=nil)
assert_generates "/products/1", :controller => 'catalog', :action => 'view', :id => '1'
# assert_recognizes(expected_options, path, extras={}, message=nil)
assert_recognizes({ :controller => "catalog", :action => "view", :id => "2" }, "/products/2")
# assert_routing(path, options, defaults={}, extras={}, message=nil)
assert_routing({ :path => "/products/3", :method => :get },
{ :controller => "catalog", :action => "view", :id => "3" })
- Rspec-2 for Rails-3
match ':controller(/:action(/:id(.:format)))'
match '/login' => 'accounts#login', :as => 'login'
# Use root as a shorthand to name a route for the root path “/”.
root :to => 'blogs#index'
match '/articles/:year/:month/:day' => 'articles#find_by_id', :constraints => {
:year => /\d{4}/,
:month => /\d{1,2}/,
:day => /\d{1,2}/
}
...
...
...