ほげほげパッチ

有る事無い事 徒然なるままに

アソシエーション Lv.2

3角関係の時のアソシエーション

 A
 ↕︎ ↘︎
 B ↔︎ C  みたいなとき

書き方

  • アソシエーションの書き方は一緒。
     Aさん->Bさん
     Aさん->Cさん
     Bさん->Aさん
     Bさん->Cさん
     Cさん->Aさん
     Cさん->Bさん
    をそれぞれ全部書く。(belongs_to か has_many)

ルーティングできない

  • 普通にルーティングすると問題が起きる(うまく紐づかない)
  resources :comments, only: :create

通常のcreateアクションのパスでは、user_id、tweet_idがパラメーターとして載ってこない。
'POST' '/tweets(.:format)' 'tweets#create'

解 = ネスト

  • ルーティングのネスト*1で解消
    親子関係が明示されることで、紐付け先のidを自動でパラメーターに乗せてくれるっぽい。
Rails.application.routes.draw do
  resources :親となるコントローラー do
    resources :子となるコントローラー
  end
end
Rails.application.routes.draw do
  resources :tweets do
    resources :comments, only: :create
  end
end

(doとend忘れそう。 )

'tweet_comments' 'POST' '/tweets/:tweet_id/comments(.:format)' 'comments#create'

└親の方のid(:tweet_id)がURLに乗ってくる。 (「このtweetに紐づくコメントですよ」が作れる。)

class CommentsController < ApplicationController
  def create
    Comment.create(comment_params)
    redirect_to "/tweets/#{comment.tweet.id}"
     # comment -> アソtweet -> idの取得 2段階
  end
  private
  def comment_params
    params.require(:comment).permit(:text).merge(user_id: current_user.id, tweet_id: params[:tweet_id])
  end
end
└ストロングパラメータ + merge*2で必要なid情報を付加する

まとめ

2人のアソシエーション => 互いに belongs_toかhas_manyを記載
3人以上の  〃    => 互いに belongs_toかhas_manyを記載
            + 親子関係をルーティングに表示(==ネスト)



*1:nest:古英語の nest「鳥の巣、居心地の良い隠れ家」 -> 巣、入れ子

*2:merge:水にひたして混ぜる -> 結合する