141
118

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

railsのroutingで出てくる:idを変更する場合

Last updated at Posted at 2014-10-12

普通にroutingを書いていくとデフォルトで以下のような感じになる。

※rails5でも動作確認を取りました。

例)スケジュール管理系のアプリを作ったと想定

config/routes.rb
Rails.application.routes.draw do
  resources :schedules
end
$ ./bin/rake routes
             Prefix Verb   URI Pattern                          Controller#Action
          schedules GET    /schedules(.:format)                 schedules#index
                    POST   /schedules(.:format)                 schedules#create
       new_schedule GET    /schedules/new(.:format)             schedules#new
      edit_schedule GET    /schedules/:id/edit(.:format)        schedules#edit
           schedule GET    /schedules/:id(.:format)             schedules#show
                    PATCH  /schedules/:id(.:format)             schedules#update
                    PUT    /schedules/:id(.:format)             schedules#update
                    DELETE /schedules/:id(.:format)             schedules#destroy

これの:idが自分の作成した意図と合わない、しっくりこない場合がある。
たとえば:idを:dateに変更した場合とか

リファレンスをググってもなかなか出てこないのでソースを見てみた。

actionpack-4.1.6/lib/action_dispatch/routing/mapper.rb

        # [:param]
        #   Overrides the default resource identifier `:id` (name of the
        #   dynamic segment used to generate the routes).
        #   You can access that segment from your controller using
        #   <tt>params[<:param>]</tt>.

コメントにしっかり書いてあった。
どうやらググり方が悪かったようである。

コメント通りルーティングを書き換えてみる。

paramを追加する必要があるのでparam: :dateを追加

config/routes.rb
Rails.application.routes.draw do
  resources :schedules, param: :date
end
$ ./bin/rake routes
             Prefix Verb   URI Pattern                          Controller#Action
          schedules GET    /schedules(.:format)                 schedules#index
                    POST   /schedules(.:format)                 schedules#create
       new_schedule GET    /schedules/new(.:format)             schedules#new
      edit_schedule GET    /schedules/:date/edit(.:format)      schedules#edit
           schedule GET    /schedules/:date(.:format)           schedules#show
                    PATCH  /schedules/:date(.:format)           schedules#update
                    PUT    /schedules/:date(.:format)           schedules#update
                    DELETE /schedules/:date(.:format)           schedules#destroy

期待通りの結果となり、params[:date]で取得できるようになった。

141
118
3

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
141
118

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?