我正在尝试在用户对文章发表评论时实施通知。我已经按照本教程https://gorails.com/episodes/in-app-navbar-notifications
进行了操作但我不知道为什么文章和通知之间没有认可的关联。在rails控制台中复制并粘贴“Notification.first.notifiable.article”会产生结果。
错误讯息here
通知视图文件夹中的index.json.jbuilder:
要求“json”
json.array! @notifications do |notification|
json.id notification.id
json.unread !notification.read_at?
json.template render partial: "notifications/#{notification.notifiable_type.underscore.pluralize}/#{notification.action}", locals: {notification: notification}, formats: [:html]
end
更新
_posted.html.erb(代码行将呈现的部分内容: json.template渲染部分:“notifications /#{notification.notifiable_type.underscore.pluralize} /#{notification.action}”....)
<%= link_to article_path(notification.notifiable.article, anchor: dom_id(notification.notifiable)), class: "dropdown-item #{"unread" if !notification.read_at?}" do %>
<%= notification.actor.name %>
<%= notification.action %>
a <%= notification.notifiable_type.underscore.humanize.downcase %>
<% end %>
通知控制器
class NotificationsController < ApplicationController
def index
@notifications = Notification.where(recipient: current_user)
end
def mark_as read
@notifications = Notification.where(recipient: current).unread
@notifications.update.all(read_at: Time.zone.now)
render json: {success: true}
end
end
评论控制器
class CommentsController < ApplicationController
before_action :authenticate_user!
before_action :set_article
before_action :set_comment, only: [:destroy, :edit, :update]
def create
@comment = @article.comments.new(comment_params)
@comment.user = current_user
respond_to do |format|
if @comment.save
Notification.create!(recipient: @article.user, actor: current_user, action: "posted", notifiable: @comment)
redirect_to @article
else
redirect_to @article
end
end
end
private
def set_article
@article = Article.find(params[:article_id])
end
def set_comment
@comment = @article.comments.find(params[:id])
end
def comment_params
params.require(:comment).permit(:content)
end
end