rails 1つの詳細ページに全てのコメントが表示される 初心者なので凡ミスかもしれませんがご教授ください
Q&A
Closed
解決したいこと
各詳細ページに各コメントを表示させたい
Ruby on RailsでTwitterのようなWebアプリをつくっています。
コメントを投稿する機能の実装中に問題が発生しました。
解決方法を教えて下さい。
コメント機能は
https://qiita.com/W2020T/items/8a3cddffda427591fa62
こちらの記事を元に作っています
変更した点はhtml.erbくらいです
現状エラーは起きていません
現段階の問題点はコメントすると一番初めに投稿された投稿詳細ページに全てのコメントが集まってしまい、コメントしたい詳細ページにはコメントが投稿できない状態です。
該当するソースコード
comment.rb
belongs_to :user
belongs_to :post
validates :content, { presence: true, length: { maximum: 100 } }
comments_controller.rb
before_action :authenticate_user
def create
@post = Post.find_by(params[:post_id])
@comments = Comment.new(
content: params[:content],
user_id: @current_user.id,
post_id: @post.id
)
if @comments.save
flash[:notice] = 'コメントを作成しました'
redirect_to("/posts/#{params[:post_id]}")
else
flash[:notice] = 'コメントの作成に失敗しました'
redirect_to("/posts/#{params[:post_id]}")
end
end
def destroy
@post = Post.find_by(params[:post_id])
@comments = Comment.find_by(params[:id])
@comments.destroy
flash[:notice] = 'コメントを削除しました'
redirect_to("/posts/#{params[:post_id]}")
end
posts_controller.rb
def show
@post = Post.find_by(id: params[:id])
@user = @post.user
@likes = Like.where(user_id: @user.id)
@likes_count = Like.where(post_id: @post.id).count
@comments = Comment.all
@comment = Comment.new
@post_detail = Post.find(params[:id])
if @current_user.present?
unless ViewCount.find_by(user_id: @current_user.id, post_id: @post_detail.id)
@current_user.view_counts.create(post_id: @post_detail.id)
end
end
end
show.html.erb
<h2>コメント一覧</h2>
<% @comments.each do |comment| %>
<div class="posts-index-item">
<div class="post-left">
<% if comment.user.avatar? %>
<%= link_to (image_tag @user.avatar_url), "/users/#{@user.id}" %>
<% else %>
<%= link_to (image_tag src="default.jpg"), "/users/#{@user.id}" %>
<% end %>
</div>
<div class="post-right">
<div class="post-user-name">
<%= link_to(comment.user.name, "/users/#{comment.user.id}") %>
</div>
<div class="post-title">
<p><%= comment.content %></p>
</div>
<div class="post-menus">
<% if @current_user && comment.user_id == @current_user.id %>
<%= link_to("削除", "/comments/#{@post.id}/destroy", {method: "post"}) %>
<% end %>
</div>
</div>
</div>
<% end %>
<%= form_tag("/comments/:post_id/create") do %>
<div class="form">
<div class="form-body">
<textarea name="content"><%= @comment.content %></textarea>
<input type="submit" value="コメントする">
</div>
</div>
<% end %>
どこに原因があるのかもわからない状態です。
ご教授いただけると幸いです。
最後まで見ていただいてありがとうございます。
0 likes