【发布时间】:2017-02-17 14:28:22
【问题描述】:
我目前正在学习 Rails,但在尝试添加评论时遇到了问题。 如果用户 A 进入用户 B 的帖子下,则评论将显示在用户 A 的所有帖子下,而不是用户 B 的特定帖子下。
我认为问题与视图页面有关,而不是与评论如何保存到数据库有关。
comment.rb
class Comment < ApplicationRecord
belongs_to :user
belongs_to :pin
end
cmets.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
关于如何解决这个问题的任何想法?
编辑。
评论表:
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
【问题讨论】:
标签: ruby-on-rails ruby model-view-controller