LoginSignup
0
0

More than 1 year has passed since last update.

TECH CAMP12日目 ~ルーティングのネスト~

Posted at

ルーティングのネスト

  • ルーティングのネストとは、段階に分けてルーティングを記述すること

書き方の例

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

メリット

  • ルーティングの記述をネストさせるとURLの階層構造ができる。
    上記のようにルーティングした場合のURL
    /tweets/id(数字)/comments
    このようにどのツイートに対してのコメントなのかが一目でわかる。

  • パラメーターに親要素のカラムを入れることができる
    ちょっと分かりにくいので使わなかったらどうなるか↓

使わなかったら...

例)

Rails.application.routes.draw do
  resources :tweets 
  resources :comments
end
html.erb
<%= form_with 'hoge', comments_path, method: :post %>

comments_pathにはどのツイートのコメントなのかを表すパラメーターがない
コメントコントローラーでは

def create
  @tweet = Tweet.find(params [:tweet_id])
  @comment = @tweet.comment.new
end

上のようなtweet_idをパラメーターとして持たせることができない。

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