【发布时间】:2015-08-27 17:25:51
【问题描述】:
在朋友的帮助下,我得到了正确设置 Comment 和 Notification 的 user_id:
[2] pry(main)> Comment.find(8)
id: 8,
content: "test",
goal_id: nil,
habit_id: nil,
valuation_id: 9,
quantified_id: nil,
commentable_id: nil,
commentable_type: nil,
user_id: 1,
created_at: Thu, 11 Jun 2015 19:57:26 UTC +00:00,
updated_at: Thu, 11 Jun 2015 19:57:26 UTC +00:00,
likes: nil>
[3] pry(main)> Comment.find(9)
id: 9,
content: "test",
goal_id: nil,
habit_id: nil,
valuation_id: 2,
quantified_id: nil,
commentable_id: nil,
commentable_type: nil,
user_id: 2,
created_at: Thu, 11 Jun 2015 19:57:55 UTC +00:00,
updated_at: Thu, 11 Jun 2015 19:57:55 UTC +00:00,
likes: nil>
[4] pry(main)> Notification.find(8)
id: 8,
habit_id: nil,
quantified_id: nil,
valuation_id: 9,
goal_id: nil,
comment_id: 8,
user_id: 1,
habit_like_id: nil,
quantified_like_id: nil,
valuation_like_id: nil,
goal_like_id: nil,
followed_id: nil,
comment_like_id: nil,
read: true,
created_at: Thu, 11 Jun 2015 19:57:26 UTC +00:00,
updated_at: Thu, 11 Jun 2015 19:57:29 UTC +00:00>
[5] pry(main)> Notification.find(10)
id: 10,
habit_id: nil,
quantified_id: nil,
valuation_id: 3,
goal_id: nil,
comment_id: 10,
user_id: 2,
habit_like_id: nil,
quantified_like_id: nil,
valuation_like_id: nil,
goal_like_id: nil,
followed_id: nil,
comment_like_id: nil,
read: true,
created_at: Thu, 11 Jun 2015 20:00:14 UTC +00:00,
updated_at: Thu, 11 Jun 2015 20:00:30 UTC +00:00>
但现在user_id 仍然没有在部分中显示正确的 id。尽管rails console 清楚地显示有人说 2,但所有通知仍然显示“1 评论了您的价值”。
notifications_controller
class NotificationsController < ApplicationController
before_action :correct_user, only: [:destroy]
def index
@notifications = current_user.notifications
@notifications.each do |notification|
notification.update_attribute(:read, true)
end
end
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 :habit
belongs_to :quantified
belongs_to :valuation
belongs_to :goal
belongs_to :user
validates :user, presence: true
private
def create_notification
@valuation = Valuation.find_by(self.valuation_id)
@user = User.find_by(@valuation.user_id).id
self.notifications.create(
valuation: self.valuation,
user: self.valuation.user,
read: false
)
end
end
通知/_notifications
<%= link_to Comment.find_by(notification.user_id).user.id, user_path(Comment.find_by(notification.comment_id).user.id) %> commented on <%= link_to "your value", notification_valuation_path(notification, notification.valuation_id) %>
【问题讨论】:
-
为什么在每次页面加载时更新所有通知?而且您不应该在视图层上使用数据库。您展示了您的通知模板,但您如何遍历通知?
标签: ruby-on-rails ruby model-view-controller notifications