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

[Rails6]Scaffoldで生成した投稿機能とdeviseで生成したユーザー機能を結びつける方法

Last updated at Posted at 2020-11-03

はじめに

Railsで記事投稿アプリを作ろうと思い、手順をカットするためにScaffoldを導入したところ、投稿とユーザーを結びつけるのに躓いたので知見を共有
詳しく知りたい人はこちらのドキュメントをどうぞ

前準備

Scaffoldで投稿機能生成

まずはScaffoldで投稿機能を生成。めちゃくちゃ簡単。db:migrate忘れずに

$ rails g scaffold Post content:string
$ rails db:migrate

devise

こちらの記事を参考に。めっちゃ分かりやすい

紐づけ

belongs_toとhas_many

app/models/user.rb
class User < ApplicationRecord

  # 以下を追加.複数形のsを忘れずに
  has_many :posts,  dependent: :destroy
end
app/models/post.rb
class Tip < ApplicationRecord
  # 以下を追加.念のため、空の投稿は拒否されるようにする
  belongs_to :user
  validates :content, presence: true
end

user_idカラムの追加

$ rails g migration add_user_id_to_posts user_id:integer
$ rails db:migrate

これで仕組み上はUserモデルとPostモデルの紐づけが完了した

controllerに追加

app/controllers/posts_controller.rb
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def post_params
      params.require(:post).permit(:content)
    end
end

Scaffoldによって自動生成された上のコードを以下のように変更する。

app/controllers/posts_controller.rb
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

    # Only allow a list of trusted parameters through.
    def post_params
      params.require(:post).permit(:content).merge(user_id: current_user.id)
    end
end

これで完成。実行してlocalhost:3000/posts に移動し投稿してみよう‼‼

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?