moosan63の日記、技術メモ

日記とか、技術メモとか

routes.rbのnamespaceが便利

routes.rbでnamespaceがすごい便利な事に気づいたのでメモ。

例えばルーティングで下記のように階層で分けるみたいなことをするとき

get "/users/hoge" => "users/hoge#index"
get "/users/fuga"  => "users/fuga#index"
get "/admins/hoge"=> "admins/hoge#index"
get "/admins/fuga" => "admins/fuga#index"

こうかける

namespace "users" do
  get "hoge" => "hoge#index"
  get "fuga"  => "fuga#index"
end

namespace "admins" do
  get "hoge" => "hoge#index"
  get "fuga"  => "fuga#index"
end

ちゃんとコントローラーはnamespaceに対応したところに置きましょう

app/controllers/users/hoge_controller.rb
app/controllers/users/fuga_controller.rb
app/controllers/admins/hoge_controller.rb
app/controllers/admins/fuga_controller.rb

もしすでに
app/controllers/以下にいろんなコントローラーがある状態で名前空間だけ変えたい場合は

scope "users" do
  get "hoge" => "hoge#index"
  get "fuga"  => "fuga#index"
end

とやると、よい。
( /users/hogeでhoge#indexが呼ばれる。users/hoge#indexではない。)
おわり