我有一个Rails应用程序,我正在为它实现ActionCable。(坦白地说,我是RoR的高级初学者,也是ActionCable的完全新手。)我正在使用这个应用程序来了解它。)我想弄清楚我是否能做以下几件事:
想象一下您的标准聊天室(就像所有ActionCable教程中的那样),其中的转折是:
在呈现页面时,我对每条消息都有一个部分,如下所示:
# View:
<%= render :partial=>"message_line", :collection=>@messages, :locals=>{:current_user=>@user}%>
# _message_line.html.erb partial
<div><%= message_line %></div>
<div>
<% if current_user.admin or current_user.id==message_line.user.id %>
<%= Link to edit post... %>
<% end %>
</div>
我已经成功地设置了ActionCable,这样当用户输入消息时,消息就会被广播并显示在房间内所有用户的屏幕上。但是我不知道当接收到消息时,接收消息的用户是否是管理用户,因此应该显示“链接到编辑post”链接。调用控制器操作将消息推送给其他人的用户不是接收消息的用户,因此控制器不知道接收用户是否是管理员(特别是考虑到有多个接收者)。
作为一个具体示例,请考虑以下设置:
聊天室里有三个用户,UserA,UserB,UserC。UserA是管理员,UserB和UserC不是。
下面是应该发生的事情:
提前感谢您的帮助!
发布于 2021-02-13 07:06:21
基于this answer,看起来您的部分在发送之前正在呈现。这意味着您的部分中的current_user
是发送用户,而不是查看用户,正如您可能预期的那样。
我建议在这里做同样的事。呈现两个不同的部分,然后使用查看用户的权限来确定使用哪个部分。
# controller
data[:htmlAdmin] = ApplicationController.render partial: 'partial1', locals: { message: message_line, admin: true }
data[:htmlUser] = ApplicationController.render partial: 'partial2', locals: { message: message_line, admin: false }
# partial1
<div><%= message_line %></div>
<div>
<%= Link to edit post... %>
</div>
# partial2
<div><%= message_line %></div>
# channel
received(data) {
if current_user.is_admin?
$("#messages_div").prepend(data[:htmlAdmin].html)
else
$("#messages_div").prepend(data[:htmlUser].html)
end
}
编辑
如果使用current_user,就可以以这种方式在ActionCable中获得以下内容:
# app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
protected
def find_verified_user
if current_user = env["warden"].user
current_user
else
reject_unauthorized_connection
end
end
end
end
https://stackoverflow.com/questions/66186217
复制相似问题