LoginSignup
10
7

More than 3 years have passed since last update.

resourcesメソッドについて

Posted at

resourcesメソッドでルーティングに追加される内容

勉強しているとresoucesメソッドが出てきて、あまり内容を理解せずにアプリに実装したので、調べてみました。

resources :tweets

routes.rb
Rails.application.routes.draw do
  resources :tweets
end

このように記述するだけで

URL アクション HTTPメソッド
/tweets tweets#index GET
/tweets/:id tweets#show GET
/tweets/new tweets#new GET
/tweets tweets#create POST
/tweets/:id/edit tweets#edit GET
/tweets/:id tweets#update PATCH
tweets:id tweets#destroy DELETE

これだけの基本的なルーティングが一気通貫でできてしまいます。便利ですね。同時にヘルパーも生成されるようですが、ここでは割愛します。

resources :tweetsの中に:commentsをネスト

もちろんネストにも対応しているので、あるtweet_idが複数のコメントを持っていた場合などは

routes.rb
Rails.application.routes.draw do
  resources :tweets do
    resources :comments
  end
end
URL アクション HTTPメソッド
tweets/:tweet_id/comments comments#index GET
/tweets/:tweet_id/comments/:id comments#show GET
/tweets/:tweet_id/comments/new comments#new GET
/tweets/:tweet_id/comments comments#create POST
/tweets//:tweet_id/comments/:id/edit comments#edit GET
/tweets/:tweet_id/comments/:id comments#update PATCH
tweets/:tweet_id/comments/:id comments#destroy DELETE

以上のようなルーティングが追加されます。

オリジナルのアクションを追加できる collection

これだけでも十分便利ですが、さらにオリジナルのアクションをresourcesに追加することもできるので、

routes.rb
Rails.application.routes.draw do
  resources :tweets do
    resources :comments
    collection do
      #HTTPメソッド名 :アクション名
      get :preserve
    end
  end
end

こうすることで、tweetsのルーティングの中にpreserveアクションを追加できるので、開発の幅がひろがりますね。

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