LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】コメント機能をAjax実装① 準備編

Last updated at Posted at 2022-06-27

コメント機能を実装したので、記録を残します___φ(•ᴗ•๑)
間違っている箇所があれば、ご指摘頂けると大変助かります。

実装内容

・投稿記事に対してコメント機能をつける
・ログインユーザーのみコメント可能
・投稿・削除・更新を非同期で実装する

前提

・Rails6
・Devise導入済
・jQuery導入済
・Bootstrap5
・記事投稿機能を実装済

準備

(1)Commentモデルを作成

Commentモデルに、user_idとpost_idを忘れずに追加します。

rails g model Comment body:text user_id:integer post_id:integer
rails g db:migrate

モデルにアソシエーションとバリデーションを追加します。

comment.rb
class Comment < ApplicationRecord
  belongs_to :user
  belongs_to :post

  validates :body, presence: true
  validates :user_id, presence: true
  validates :post_id, presence: true
end

Postモデルもhas_many :commentsを追加

Post.rb
class Post < ApplicationRecord
  belongs_to :user
  has_many :comments, dependent: :destroy
  #~~省略~~
end

(2)Commentコントローラーを作成

 rails g controller comments

(3)ルーティングの定義

postsの中にcommentsをネストします。

routes.rb
Rails.application.routes.draw do
   #~~省略~~
  resources :posts do
    resources :comments
  end
  #~~省略~~
end

以上で準備が整いましたので、実際に投稿機能を実装します。
続きはこちら→【Rails】コメント機能Ajax実装② 投稿編

関連記事

【Rails】コメント機能Ajax実装② 投稿編
【Rails】コメント機能Ajax実装③ 削除編
【Rails】コメント機能Ajax実装④ 更新編

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