LoginSignup
101
121

More than 5 years have passed since last update.

railsでユーザーと投稿を紐付ける

Posted at

前にポストしたユーザー機能と投稿機能の続き。今度はユーザーと投稿を紐付ける。大枠としてはポストのDBにユーザーのidカラムを準備し、誰が投稿したかを分かるようにする。

postsテーブルにuser_idカラムを追加

  • rails g migrationでファイルを追加
  • マイグレーションファイルのchangeメソッドにカラムを追加する旨記載
  • rails db:migrateでマイグレーションファイルを反映

投稿時にuser_idをDBに保存する

userの値が現在ログインしているユーザーのものになるようにする。

test
def create
  @post = Post.new(
    content: params[:content],
    user_id: @current_user.id
  )
end

@current_user.idは下記で引っ張ってくる。これはapplication_controller.rbに記載し、どこでも使えるようにする。

test
before_action :set_current_user

def set_current_user
  @current_user = User.find_by(id: session[:user_id])
end

投稿にユーザー名を表示したい時

test
  def show
    @post = Post.find_by(id: params[:id])
    # 変数@userを定義してください
    @user = User.find_by(id: @post.user_id)
  end

@postにユーザー情報を入れ、そのユーザー情報のidを@userに入れる。今回は投稿に紐付いているユーザー名を表示なので投稿の情報からuser_idをひっぱり、それからuser情報をひっぱる。

投稿者だけが編集・削除ができるようにする

投稿者だけが編集できるようにensure_correct_userという現在のuser_idと投稿者のidが一致していないとはじくメソッドを作る。posts_controllerに作成する。どのcontrollerかはどのviewで制御するのかによる。controllerをまたぐ場合はapplicationで設定したほうが良さそう。

post_controller
  def ensure_correct_user
    @post = Post.find_by(id:params[:id])
    if @post.user_id != @current_user.id
      flash[:notice] = "権限がありません"
      redirect_to("/posts/index")
  end

postクラスからuser_idをUserクラスから作ったcurrent_userからはidを取得しそれが一致していない場合、indexに飛ばすように設定。

101
121
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
101
121