【rails】memberとcollectionでアクションを増やす
memberとcollectionとは
railsには定番のアクションがある
定番のアクション7種類
new、create、index、show、edit、updata、destroy
関連記事:【rails】CRUD機能まとめ
この定番7種類のほかにアクションを追加したいとき、
memberやcollectionを使う
memberの場合
resources :photos do
member do
get 'preview'
end
end
/photos/1、/photos、/photos/1/previewのようにurlの種類が増える
例)routes.rbで「like」について以下のように書き換えてみる
resources :articles do
resources :comments, only: [:index, :new, :create]
member do
post 'like'
end
like_article_path(postリクエスト) → articles#showだったのが、articles#likeに変わる
collectionの場合
resources :photos do
collection do
get 'search
end
end
/photos/1、/photos、/photos/searchのようにurlの種類が増える
memberとの違いは、idを指定しないとき「/photos/search」のようになる
searchの場合、photos全体からsearchするので、idがないのは自然なことと言える
このケースだと、memberじゃなくcollectionを使うのが◎
例)profileにpublish(公開)アクションを作るとする
resource :profile, only: [:show, :edit, :update] do
collection do
post 'publish'
end
end
publish_profile_path → profiles#publishが出来上がる
ただrailsにおいては、定番の7種類のみ使うほうがわかりやすくまとまる(RESTfulという考え方)
#DAY12