ネットの海の片隅で

技術ネタの放流、あるいは不法投棄。

Railsのresourcesにcollection, member以外を指定したい

前提

Railsのrouting設定では、一般的に以下のような書き方をする。

# config/routes.rb
Rails.application.routes.draw do
  resources :posts
end

このとき、最新の記事を公開するURLとして/posts/latestが欲しい場合、次の2つの書き方が考えられる。

A

Rails.application.routes.draw do
  resources :posts
  get "posts/latest" => "posts#latest"
end

B

Rails.application.routes.draw do
  resources :posts do
    get :latest, on: :collection
  end
end

問題

A

  • resoucesとgetが分離されているため、postsの下にlatestがあることがわかりにくい

B

  • 明らかにcollectionじゃないものに対してcollectionを指定している

例えばこう書きたい

Rails.application.routes.draw do
  resources :posts do
    get :latest, on: :singleton
  end
end

さいごに

  • 「こうすると良いよー」
  • 「いや、こうかけよks」

など、お待ちしております。