LoginSignup
2
2

More than 3 years have passed since last update.

ルーティングのネスト ❏Rails❏

Last updated at Posted at 2019-11-27

いつ使うの

ツイートにコメントできるようにする時を考えます。
コメントのparamsの中に、どのツイートに対してのコメントなのかわかるようにそのツイートのid情報を含めます。

やり方→ルーティングをネストさせる

実際に例を見たほうが早いです。

routes.rb
Rails.application.routes.draw do
  resources :tweets do
    resources :comments, only: [:create, :destroy]
  end
end

このように記述し、
rails routesを叩いてルーティングを確認すると、、、

ターミナル
tweet_comments POST   /tweets/:tweet_id/comments(.:format)                                                     comments#create
 tweet_comment DELETE /tweets/:tweet_id/comments/:id(.:format)                                                 comments#destroy

真ん中にtweet_idが含まれてるぅ!!!
これでどのツイートに対してのコメントかわかるようになったね!!!

【注意】form_withでインスタンスを2つ渡す

haml
- form_with model: [@tweet, @comment] do |form|
  = form.text_field :text
  = form.submit

@tweetを渡すことでtweet_idを渡せるようになります。
お忘れなく。



ではまた!

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