0
我目前正在學習rails,並且在嘗試添加評論時遇到問題。 如果用戶A在用戶B的帖子下發表評論,評論將顯示在所有用戶A的帖子下,而不是用戶B的特定帖子下。ROR:添加評論發佈
我認爲問題與視圖頁面有關,而不是評論如何被保存到數據庫。
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
不限如何解決這個問題的想法?
編輯。
評論表:
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
當我嘗試,我得到一個未定義的方法錯誤:未定義的方法徵求意見#<針:0x9560868>另一個新手的錯誤,但我不不知道是什麼導致了錯誤。爲什麼當我把'pin.user.comments'放到了'pin.comments'的時候卻不能工作? – BigL
您可以在保存評論時驗證PIN碼是否已保存?就像db列中的數據一樣? –
是的,我會編輯原始問題來顯示這 – BigL