我正在学习rails并且在尝试添加评论时遇到问题。 如果用户A在用户B的帖子下发表评论,评论将显示在所有用户A的帖子下,而不是在用户B的特定帖子下。
我认为问题与视图页面有关,而不是如何将注释保存到数据库。
comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :pin
end
comments.controller.rb
class CommentsController < ApplicationController
before_action :set_pin
def create
@comment = @pin.user.comments.build(comment_params)
@comment.user_id = current_user.id
if @comment.save
redirect_to root_path
else
render root_path
end
end
private
def comment_params
params.require(:comment).permit(:content)
end
def set_pin
@pin = Pin.find(params[:pin_id])
end
end
index.html.erb
- if pin.user.comments
- pin.user.comments.each do |comment|
.commentContainer
%h4.desc
%strong
=link_to (pin.user.Username), user_path(pin.user_id)
= comment.content
有关如何解决此问题的任何想法?
EDIT。
评论表:
0|id|INTEGER|1||1
1|user_id|integer|0||0
2|pin_id|integer|0||0
3|content|text|0||0
4|created_at|datetime|1||0
5|updated_at|datetime|1||0
sqlite> select * from comments;
1|15||Nice shot!|2017-02-07 16:13:06.707372|2017-02-07 16:13:06.707372
2|15||Cool pic|2017-02-07 16:25:27.780830|2017-02-07 16:25:27.780830
3|14||test|2017-02-08 14:08:17.397782|2017-02-08 14:08:17.397782
答案 0 :(得分:0)
我相信你是对的,问题就在于你如何展示它们。
您想要删除用户显示评论。你想要做的是显示属于该引脚的注释列表,然后通过它访问用户的数据。
- if pin.comments
- pin.comments.each do |comment|
.commentContainer
%h4.desc
%strong
=link_to (comment.user.Username),user_path(comment.user.user_id)
= comment.content
该行
- pin.comments.each do |comment|
无论用户如何,都会显示属于该引脚的所有评论。然后通过它与内部注释的关系来访问用户的数据。
(comment.user.Username)
还要确保所有关系都是双向的。
Pin.rb
has_many :comments
User.rb
has_many :comments