読者です 読者をやめる 読者になる 読者になる

yo_waka's blog

418 I'm a teapot

Railsのroutes.rbでscopeとpathが便利だった

なんか日本語が不自由な感じ。。
Railsのroutes.rbで普通にresource(s)を使う場合はidを使ったURLルートが作られる。

resource 'foo' do
  resources 'bars'
end

# bundle exec routes
GET    /foo/:foo_id/bars(.:format)             bars#index
POST   /foo/:foo_id/bars(.:format)             bars#create
GET    /foo/:foo_id/bars/new(.:format)         bars#new
GET    /foo/:foo_id/bars/:id/edit(.:format)    bars#edit
GET    /foo/:foo_id/bars/:id(.:format)         bars#show
PATCH  /foo/:foo_id/bars/:id(.:format)         bars#update
PUT    /foo/:foo_id/bars/:id(.:format)         bars#update
DELETE /foo/:foo_id/bars/:id(.:format)         bars#destroy
POST   /foo(.:format)                         foo#create
GET    /foo/new(.:format)                     foo#new
GET    /foo/:id/edit(.:format)                foo#edit
GET    /foo/:id(.:format)                     foo#show
PATCH  /foo/:id(.:format)                     foo#update
PUT    /foo/:id(.:format)                     foo#update
DELETE /foo/:id(.:format)                     foo#destroy


でもidを見せたくなくて、ランダムなトークンでアクセスURLを作りたいとき。
「/foo/:id」ではなくて「/:token」、「/foo/:foo_id/bars」ではなくて「/:token/bars」でアクセスさせたい。
そういうときはscopeとpathを使うとスッキリ書ける。

scope ':token', :token => /\w{8}/ do
  resource 'foo', :path => '/' do
    resources 'bars'
  end
end

# bundle exec rake routes
GET    /:token/bars(.:format)                  bars#index {:token=>/\w{8}/}
POST   /:token/bars(.:format)                  bars#create {:token=>/\w{8}/}
GET    /:token/bars/new(.:format)              bars#new {:token=>/\w{8}/}
GET    /:token/bars/:id/edit(.:format)         bars#edit {:token=>/\w{8}/}
GET    /:token/bars/:id(.:format)              bars#show {:token=>/\w{8}/}
PATCH  /:token/bars/:id(.:format)              bars#update {:token=>/\w{8}/}
PUT    /:token/bars/:id(.:format)              bars#update {:token=>/\w{8}/}
DELETE /:token/bars/:id(.:format)              bars#destroy {:token=>/\w{8}/}
POST   /:token(.:format)                      foo#create {:token=>/\w{8}/}
GET    /:token/new(.:format)                  foo#new {:token=>/\w{8}/}
GET    /:token/edit(.:format)                 foo#edit {:token=>/\w{8}/}
GET    /:token(.:format)                      foo#show {:token=>/\w{8}/}
PATCH  /:token(.:format)                      foo#update {:token=>/\w{8}/}
PUT    /:token(.:format)                      foo#update {:token=>/\w{8}/}
DELETE /:token(.:format)                      foo#destroy {:token=>/\w{8}/}

あとは必要に応じて:onlyと:exceptでアクションを絞るだけ。