实际上我需要一个很大的帮助,我正在使用 rails 5.1.4
,我在使用 ActionCable 和后台作业渲染部分时卡住了。在我的部分,我有一个条件 current_user
检查是否 current_user
是消息所有者并使用绿色获取他的用户名以做出一些不同,到目前为止,在房间对话中为他是所有者的每条消息显示一个更新和删除按钮。但是,如果我刷新页面或删除 current_user
在渲染之前的部分工作。但是,我希望这种情况发生。或者,如果有的话,寻找最好的方法。提前致谢。
这是我的终端中显示的错误:
ERROR: ActionView::Template::Error: Devise could not find the warden::Proxy instance on your request environment.
这些是我的文件内容。
部分:_conversation.html.erb
<div id="message">
<% if conversation.user == current_user %>
<span style="text-align: center; color: green"><%= conversation.user.username %>
</span>
<% else %>
<span style="text-align: center; color: magenta"><%=
conversation.user.username %></span>
<% end %>
<p style="color: black"><%= conversation.body %></p>
</div>
Message_controller.rb
def create
conversation = @room.conversations.new(conversation_params)
conversation.user = current_user
conversation.save
MessageRelayJob.perform_later(conversation)
End
房间/show.html
<div id="conversations" data-room-id="<%= @room.id %>">
<%= render @room.conversations %>
</div>
我的工作类别
class MessageRelayJob < ApplicationJob
queue_as :default
def perform(conversation)
ActionCable.server.broadcast "room_tchats_#{conversation.room.id}_channel",
conversation: render_conversation(conversation)
end
private
def render_conversation(conversation)
ConversationsController.render partial: 'conversations/conversation', locals: {conversation: conversation}
end
end
最佳答案
当您尝试获取 Devise current_user
时可能会发生这种情况在由 Action 电缆管理的代码的某些部分中。就像一个后台作业来呈现评论或其他东西。您可以通过在 Controller 中使用类似以下内容来解决它,因为您无法在模型或工作级别访问守望者(根据我的有限知识):(我在 CommentsController 创建操作中创建我的评论后立即调用工作,它调用呈现包含编辑和删除按钮的评论部分的私有(private)方法,需要 current_user)
def create
@product = Product.find(comment_params[:product_id])
@comment = @product.comments.build(comment_params)
@comment.save!
gon.comment_id = @comment.id
gon.comment_user_id = @comment.user_id
ActionCable.server.broadcast "chat", comment: render_comment
render :create, layout: false
end
def render_comment
CommentsController.renderer.instance_variable_set(:@env, {"HTTP_HOST"=>"localhost:3000",
"HTTPS"=>"off",
"REQUEST_METHOD"=>"GET",
"SCRIPT_NAME"=>"",
"warden" => warden})
CommentsController.render(
partial: 'comments/comment_detail',
locals: {
product: @product,
comment: @comment
}
)
end
这将帮助您解决守望者问题,如果您在该部分中使用了 devise 的 current_user,它将为您提供评论用户(因为该用户启动了部分的渲染,因此应该如此)。现在要解决这个问题,如果您有一个前端框架,您可能需要从 cookie 中获取当前用户,以限制某些操作,例如编辑/删除。但是如果您在纯rails中工作,我遇到的解决方案是您必须在具有当前用户ID的dom中创建一个隐藏字段,并且您将获取该ID以在脚本中进行比较。您可能需要在 javascript 中访问 rails 变量,为此您可以使用 冈 gem 。我知道这个答案可能比要求的要多,但是我已经搜索了很多,但没有找到令人满意的解决方案,请随时讨论。
关于ruby-on-rails - rails 5.1.4 ( ActionCable + Jobs + Devise + ConversationsController.render ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48670606/