0

每當創建通知時,我們如何爲發表評論(並影響通知)的用戶設置:user_id如何設置:user_id與評論通知?

當我檢查rails console由於某種原因,所有Notifications都顯示爲user_id: 1當他們中的一些應user_id: 2因爲後者是一個誰做了評論。

我可能只是沒有足夠的理解代碼,因爲我一直沿着輸入我自己的版本沿着this tutorial

comment.rb

class Comment < ActiveRecord::Base 
    after_create :create_notification 
    has_many :notifications 
    has_many :comment_likes 
    has_many :likers, through: :comment_likes, class_name: 'User', source: :liker 
    belongs_to :valuation 
    belongs_to :user 
    validates :user, presence: true 

private 

    def create_notification # I replaced the tutorial's "Post" with my "Valuation" 
    @valuation = Valuation.find_by(self.valuation_id) 
    @user = User.find_by(@valuation.user_id).id 
    Notification.create(
    valuation_id: self.valuation_id, 
    user_id: @user, 
    comment_id: self, 
    read: false 
    ) 
    end 
end 

notifications_controller

class NotificationsController < ApplicationController 
    before_action :correct_user, only: [:destroy] 

    def index 
    @notifications = Notification.where(:user_id => current_user.id) 
    @notifications.each do |notification| 
     notification.update_attribute(:read, true) 
    end 
    end 


    def destroy 
     @notification = Notification.find(params[:id]) 
     @notification.destroy 
     redirect_to :back 
    end 

private 

    def correct_user 
    @notification = current_user.notifications.find_by(id: params[:id]) 
    redirect_to root_url, notice: "Not authorized to edit this notification" if @notification.nil? 
    end 
end 

通知/ _notification

<%= link_to Comment.find_by(notification.comment_id).user.name, user_path(Comment.find_by(notification.comment_id).user.id) %> commented on <%= link_to "your value", notification_valuation_path(notification, notification.valuation_id) %> 

請讓我知道如果你需要進一步的解釋或代碼,以幫助你幫助我: - ]

+0

的ActiveRecord#重載(在軌控制檯可以幫助http://apidock.com/rails/ActiveRecord/Base/reload)可以在Rails的控制檯方面的幫助。 [離線]本教程非常糟糕。恕我直言,這是更好的替代http://railscasts.com/episodes/406-public-activity – maringan

+0

我不知道,但我認爲如果你在你的comment.rb使用'@user = current_user',它應該解決這個問題。 'User.find_by(@valuation.user_id).id'找到誰進行了評估... – pauloancheta

+0

對不起@pauloancheta你在說'@user = current_user.find_by(@valuate.user_id).id',因爲這是給出錯誤? –

回答

0

@valuation = Valuation.find_by(self.valuation_id) 
@user = User.find_by(@valuation.user_id).id 

Notification.create(
    valuation_id: self.valuation_id, 
    user_id: @user, 
    comment_id: self, 
    read: false 
    ) 

應該

self.notifications.create(
    valuation: self.valuation, 
    user: self.valuation.user 
) 
在遷移文件集

t.boolean read, default: false 

在您的控制器中:

def index 
    @notifications = Notification.where(:user_id => current_user.id) 
    @notifications.each do |notification| 
    notification.update_attribute(:read, true) 
    end 
end 

變爲:

def index 
    @notifications = current_user.notifications 
    @notifications.each do |notification| 
    notification.update_attribute(:read, true) 
    end 
end