2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】 投稿とユーザーの紐付け(メモ)

Posted at

# 目標

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

# 環境

  • Rails: 6.1.3
  • ruby: 3.0.0
  • mac: OS

前提

  • 投稿機能実装済み

実装

1.postテーブルにuser_idカラムを追加

ターミナル
$rails g migration AddUserIdToPosts user:references
class AddUserIdToPosts < ActiveRecord::Migration[6.1]
  def change
    add_reference :posts, :user, null: false, foreign_key: true
  end
end
ターミナル
$rails db:migrtate

2.モデルにhas_manybelongs_toを記述

ユーザーは投稿が複数持てるので has_many

app/models/user.rb
class User < ApplicationRecord
  has_many :posts

1つの投稿に対して1ユーザーなのでbelongs_to

app/models/post.rb
class Post < ApplicationRecord
  belongs_to :user

3. postコントローラー記述

app/controllers/posts_controller.rb
class PostsController < ApplicationController
    
  def index
      @posts = User.posts
  end

  def show
      @post = User.posts.find(params[:id])
  end
  def create
      @post = User.posts.build(post_params)
      @post.save
      redirect_to root_url
  end
app/controllers/users_controller.rb
class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    @posts = @user.posts
  end

###4.ビュー記述
投稿詳細ページでユーザー名を表示する。

app/views/posts/show.html.erb
<h1>投稿詳細ページ</h1>
<p><%= @post.user.name %></p>
<p>内容:<%= @post.content %></p>

ユーザー詳細ページに投稿を表示する。

app/views/users/show.html.erb
 <% @posts.each do |post| %>
          <hr>
          <p>投稿内容: <%=post.content %></p>
        <% end %>

これでユーザーとの紐付きができました。
基本的なことですが備忘録として残しておきます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?