首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复“无法从({”command“subscribe”,"identifier"=>"{\"channel\":\"ConversationChannel\"}"})“{”command“=>”subscribe“,

如何修复“无法从({”command“subscribe”,"identifier"=>"{\"channel\":\"ConversationChannel\"}"})“{”command“=>”subscribe“,
EN

Stack Overflow用户
提问于 2019-01-23 14:08:58
回答 1查看 961关注 0票数 0

我正在尝试让用户将用户连接到conversation_channel,我收到了:

代码语言:javascript
复制
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,得到:

代码语言:javascript
复制
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

我的代码如下:

代码语言:javascript
复制
# 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),但对象始终为空。

EN

回答 1

Stack Overflow用户

发布于 2019-01-25 07:05:22

根据ActionCable的rails指南,您需要从cookie中获取用户id。

代码语言:javascript
复制
# 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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54320964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档