我正在使用Rails 5进行即时评论。使用Rails * .js.erb,这对于这个规模的项目来说很舒服。还可以使用ActionCable向用户提供新注释。问题是我希望ActionCable将呈现的comments / _comment.html.haml直接发送到客户端以在浏览器中评估此代码。在一般情况下,它是完全适合的。但是在评论的erb模板中我必须处理current_user以添加删除链接if current_user.admin?问题是当我调用CommentsChannel.broadcast_to并渲染_comment.html.haml渲染器时现在不是current_user。
问题是我如何使用此订阅中的当前用户呈现_comment.html.haml并将其提交给当前用户定义的每个单独订阅?
Devise用于身份验证。
评论/ _comment.html.haml
%div[comment]
.details
%span.author= comment.user.email
%span.time= l comment.created_at, format: :short
= comment.body
= link_to t('common.reply'), comment, class: 'reply-link'
= link_to t('common.delete'), comment, method: :delete, remote: true if current_user.admin?
= render 'comments/form', comment: comment.commentable.comment_threads.build, parent: comment
- if comment.children.any?
.child-comments
= render comment.children.sort_by { |c| c.created_at }.reverse
application_cable / connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
def find_verified_user
if verified_user = env['warden'].user
verified_user
else
reject_unauthorized_connection
end
end
end
end
broadcast_comment_job.rb
class BroadcastCommentJob < ApplicationJob
queue_as :default
def perform(comment)
CommentsChannel.broadcast_to \
comment.commentable,
comment: render_comment(comment)
end
private
def render_comment(comment)
CommentsController.render(partial: 'comment', locals: { comment: comment })
end
end
comment.rb
class Comment < ActiveRecord::Base
...
after_create_commit { BroadcastCommentJob.perform_now(self) }
...
end