LoginSignup
0
0

More than 3 years have passed since last update.

Rails ユーザーと投稿の紐付け

Posted at

ユーザーと投稿の紐付け

まずはpostテーブル(投稿用テーブル)にuser_idというカラムを追加する為にマイグレーションファイルを作成します。

  $ rails g migration add_user_id_to_posts

そしてchangeメソッド内にadd_column :posts,:user_id,:integerを追加します

add_user_id_to_posts.rb
  def change
    add_column :posts,:user_id,:integer
  end

変更を反映させる為db:migrateします

  $ rails db:migrate

これでpostsテーブル内にuser_idカラムが追加されました。

そして次はpostコントローラー内のcreateアクション(投稿を作成するアクション)でuser_id: current_user.idを追加します。

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

そうするとユーザーと投稿の紐付けができる様になりました。

紐付け出来てるか確認

本当にユーザーと投稿の紐付けが出来ているか確認する為に投稿の詳細ページで投稿の作成者のみ編集、削除リンクが表示される様にします。

deviseを導入済みなのでdeviseのヘルパーメソッドのcurrent_userを使って次の様にコードを追加します。

posts/show.html.erb
  <% if @post.user_id == current_user.id %>
     <%= link_to("編集", "/posts/#{@post.id}/edit") %>
     <%= link_to("削除", "/posts/#{@post.id}/destroy", {method: "post"}) %>
  <% end %>

すると投稿者のみ編集、削除ができる様になっていると思います。

以上でユーザーと投稿の紐付け完了になります。     

お疲れしたッッ!!

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