LoginSignup
1
1

More than 5 years have passed since last update.

collectionで追加したパスの後ろにidを追加する

Posted at

やりたいこと

projectsに複数のcategoryをぶら下げ、category_idごとにビューを出すために
projects/categories/:id
↑こういうパスを作りたい。

実装方法

前準備

  • routes.rbにprojectsのリソースを追加。
  • projectsリソースにcollection do ~ endをネストさせる。
routes.rb
resources :projects do
 collection do
  //HTTPメソッド名 '生成したいパス'
 end
end

生成したいパスを指定する

上記の「生成したいパス」に以下を記述する。
get 'categories/:id', to: 'projects#category'

説明

  • resourcesで生成される7つのルーティング以外のものを生成したいときにcollectionを使用。(似たようなものにmemberがありますがここでは省略します)
  • collection内にHTTPメソッド名 'パス名/:id' to: 'コントローラ名#アクション名'を記述。

結果

ターミナル

Prefix Verb   URI Pattern                                         Controller#Action
                            //省略//
       GET    /projects/categories/:id(.:format)                  projects#category

できました。
prefix生成されないのはなんでだろう・・・?

1
1
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
1
1