ruby-on-rails - 如何修复“无法执行来自 ({"command"=>"subscribe", "identifier"=>"{\"channel\":\"ConversationChannel\"}"}) 的命令
问题描述
我正在尝试让用户将用户连接到 conversation_channel 并且我收到:
Could not execute command from ({"command"=>"subscribe", "identifier"=>" {\"channel\":\"ConversationChannel\"}"}) [NoMethodError - undefined method `id' for nil:NilClass]: /mnt/c/rails_apps/Picnotes/app/channels/conversation_channel.rb:6:in `subscribed' |
我尝试将 current_user.id 硬编码为 1 或 2,我得到了:
Started GET "/cable" for 127.0.0.1 at 2019-01-22 22:06:36 -0800
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2019-01-22 22:06:36 -0800
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
ConversationChannel is transmitting the subscription confirmation
ConversationChannel is streaming from conversations-1
我的代码如下:
# Be sure to restart your server when you modify this file. Action Cable runs in a loop that does not support auto reloading.
class ConversationChannel < ApplicationCable::Channel
# Create a unique channel for each user.
...
def subscribed
stream_from "conversations-#{current_user.id}"
end
# Removes all connected connections.
def unsubscribed
stop_all_streams
end
...
end
end
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = current_user
end
end
end
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
before_action :initiate_instance_variables
...
def current_user
@current_user ||= User.find_by(id: session[:user_id])
end
helper_method :current_user
...
end
我希望#{current_user.id}
成为用户 ID(常量:1 或 2),但对象始终为零。
解决方案
根据ActionCable的 Rails 指南,您需要从 cookie 中获取用户 ID
# 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
private
def find_verified_user
if verified_user = User.find_by(id: cookies.encrypted[:user_id])
verified_user
else
reject_unauthorized_connection
end
end
end
end
推荐阅读
- swift - 如何修复swift 4中的集合视图刷新错误
- c++ - 如何从 3D 曲面网格中移除自相交三角形?
- xaml - 如何防止在 ComboBox 关闭时单击 CheckBox?
- ruby-on-rails - 使用 mysql2 捆绑安装未在 Rails 项目中完成
- python-3.x - 将数据刮取为
- 在封装为标签的两个已知关键字之间
- javascript - 在 JavaScript 函数中检索“confirm()”值时出现 Asp.net 问题
- python - pandas.to_json 以特定形式输出日期格式
- assembly - 在装配中划分问题
- redis - 当 key 不存在时获取 BinaryJedis 的操作返回数据
- facebook - 使用 Azure B2C 和 .NET Core 2.1 时如何获取 facebook api 的访问令牌