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 コメント投稿機能(deviseなし)

2
Last updated at Posted at 2022-02-23

前提

Ruby : 2.6.5
Rails : 6.1.3
deviseは使用していません

モデル作成

$ rails g model comment content:string user_id:integer post_id:integer
$ rails db:migrate
user.rb
  has_many :comments
post.rb
  has_many :comments
comment.rb
class Comment < ApplicationRecord
  validates :content, { presence: true, length: { maximum: 100 } }
  belongs_to :user
  belongs_to :post
end

ビューの作成

posts/show.html.erb
<%= form_with(model: [@post, @comment], local: true) do |f| %>
<textarea name="content"><%= @comment.content %></textarea>
<input type="submit" value="コメントする">
<% end %>
<p>コメント件数<%= @comments.count %></p>
<% @comments.each do |c| <div>
<a href="/users/<%= c.user.id %>"><%= c.user.name %></a>
<%= c.content %>
<%= link_to("削除", "/comments/#{c.user.id}/destroy", {method: "post"}) %>
<% end %>
<%= paginate @comments %>

コントローラの作成

comments_controller.rb
def create
    post = Post.find(params[:post_id])
    @comment = post.comments.new(comment_params)
    @comment.user_id = current_user.id
    if @comment.save

      flash[:notice] = 'コメントを作成しました'
      redirect_to("/posts/#{params[:post_id]}")
    else
      flash[:notice] = 'コメントの作成に失敗しました'
      redirect_to("/posts/#{params[:post_id]}")
    end
  end
posts_controller.rb
def show
    @post = Post.find_by(id: params[:id])
    @user = @post.user
    @likes_count = Like.where(post_id: @post.id).count
    @comment = Comment.new
    @comments = @post.comments.page(params[:page]).per(7).reverse_order
  end

参考記事

【Rails】コメント機能の実装手順メモ
【Rails】コメント機能の実装
[Ruby on rails]コメント機能をつける

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?