2017-02-17 163 views
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 

回答

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 
+0

當我嘗試,我得到一個未定義的方法錯誤:未定義的方法徵求意見#<針:0x9560868>另一個新手的錯誤,但我不不知道是什麼導致了錯誤。爲什麼當我把'pin.user.comments'放到了'pin.comments'的時候卻不能工作? – BigL

+0

您可以在保存評論時驗證PIN碼是否已保存?就像db列中的數據一樣? –

+0

是的,我會編輯原始問題來顯示這 – BigL