【rails】モデルの関連付け
ポートフォリオを改修中に記憶が曖昧になったのでまとめておきます。
前置き
モデルがuser
とpost
の場合、かつuser:post = 1:多
の関係の場合
主キーと外部キーとは
今回の場合、userテーブルに元々あるidが主キーで、
あとに作る、 追加したpost テーブルにuser_idを外部キーとして
主キーを外部キーに保存することで関連付けができます
主キー側のモデル(belongs_toで指定してる側)が親と考えるとスッキリします。
モデルへの書き込み
postは一人のuserから生み出されますpost belongs_to 単数形
class Post < ApplicationRecord belongs_to :user end #これでpost belongs to userになる
userはたくさんのpostを持っているのでhas_many 複数形
class User < ApplicationRecord has_many :posts end #これでuser has many postsになる
これだけで、主キーと外部キーを認識してくれます。
add migrate
$ rails g migration add_user_reference_to_post user:references
※ここでuser_id:references
としなくても勝手にuser_id
としてテーブル側には作成してくれるので注意です。
そして
$ rails db:migarte
その結果
class AddUserToPost < ActiveRecord::Migration[5.2] def change add_reference :posts, :user, foreign_key: true end end
postコントローラー側
実際に使う場合、
class PostController < ApplicationController def create @post = Post.new(post_params.merge(user_id: current_user.id)) if @post.save redirect_to post_path(@post) else render :new end end ........... private def post_params params.require(:post).permit(:name,:description) end
view側
#postのviewの場合 @post.user.name #これでpostを投稿したuserのnameが取得てきます。