74
75

More than 5 years have passed since last update.

よく使うRouting設定

Last updated at Posted at 2012-05-18

詳しいルート定義の確認は

rake routes

ControllerやHelperの変更

Controller

routes.rb
resources :users, :controller => 'members'

Helper

routes.rb
resources :reviews, :as => 'comments'

モジュール配下のController

controllers/admin/videos_controller.rb

まずはgenerate

$ rails g controller Admin::Videos

これでAdmin::VideosControllerがcontrollers/adminにvideos_controller.rbという名前で生成される。
あとは、そのrouting設定

routes.rb
namespace 'admin' do
  resources :videos
end

/admin/videosや /admin/videos/:id といったURLパターンと、
admin_videos_pathやadmin_video_path(id)のようなUrlヘルパーが生成される。
viewsのファイルも、views/admin/videosに移動しておく。

URLパターンやUrlヘルパーに影響を与えない場合

(今回の例では、URLパターンやUrlヘルパーにadminを挿入ない場合)

routes.rb
scope :module => 'admin' do
  resources :videos
end

controllerはadmin/videos_controller.rbを参照するが、UrlヘルパーとURLパターンには影響が無くなる。(つまり、普通に"resources :videos"とした場合と一緒)

Adminモジュールに属さないものにadminが付いたURLを割り当てたい場合

(今回の例では、Videosコントローラに対して、"/admin/videos"のようなURLを割り当てる場合)

routes.rb
scope 'admin' do
  resources :videos
end

さらに

routes.rb
scope ':admin' do
  resources :videos
end

とすることで、

/:admin/videos
のような"ルートパラメータ"を含ませることが出来る。

アクションを追加する

routes.rb
resources :users do
  collection do
    get 'action_x'
  end
  member do
    get 'action_y'
  end
end

とする。アクションが1つなら

routes.rb
resources :users do
  get 'action_x', :on => :collection
  get 'action_y', :on => :member
end

とも書ける。

collectionによって
/users/action_x(.:format)
action_x_users_path, action_x_users_url

memberによって
/users/:id/action_y(.:format)
action_y_users_path, action_y_users_url

が生成される。

アクションの無効化

except

routes.rb
resources :users, :except => ['show', 'destroy']

とすることで、show, destroyアクションに関するルート定義は行われなくなる。

only

routes.rb
resources :users, :only => ['index', 'show']

とすることで、index, showアクションに関するルート定義だけしか行われなくなる。

アクションに関連づいたURLを変更する

routes.rb
resources :users, :path_names => { :new => 'atarashino', :edit => 'henko' }

とすることで、
"/users/atarashino"と"/users/:id/henko"というURLから、それぞれnew, editアクションを呼び出せる

ネスト

videosリソースがその配下にcommentsリソースを伴うとき(has_manyやbelongs_toで、アソシエーションが設定されているとき)"/videos/3/comments"のようなURLを作る。

routes.rb
resources :videos do
  resources :reviews
end

match

routes.rb
match ':controller(/:action(/:id(.:format)))'

(初めて手で打った。。。)

74
75
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
74
75