每当创建通知时,我们如何为发表评论的用户设置:user_id
(并影响通知)?
当我因某些原因检查rails console
时,所有Notifications
显示为user_id: 1
时,其中一些user_id: 2
应为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
,因为后者是进行评论的人
我可能只是不太了解代码,因为我沿着 this tutorial 继续输入我自己的版本。
comment.rb
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
notifications_controller
<%= 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) %>
通知/ _notification
List<String> value = entry.getValue();
String timeEntries = value.toString();
String after = timeEntries.replace(",", " ");
String after2 = after.replace(" ", " ");
String after3 = after2.replace("[", "");
String after4 = after3.replace("]", "");
如果您需要进一步的说明或代码来帮助我,请告诉我: - ]
答案 0 :(得分: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