ActionCable出现“未找到订阅类”问题

时间:2018-02-24 18:01:38

标签: ruby-on-rails ruby-on-rails-5 actioncable

我使用Rails 5.1.5并且我有以下代码。

应用/信道/ application_cable / channel.rb

module ApplicationCable
  class Channel < ActionCable::Channel::Base
  end
end

应用/信道/ application_cable / connection.rb

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user
    def connect
      self.current_user = find_verified_user
      logger.add_tags 'ActionCable', current_user.slug
    end
    private
    def find_verified_user
      if verified_user = env['warden']&.user
        verified_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

应用/信道/ notifications_count_channel.rb

class NotificationsCountChannel < ApplicationCable::Channel
  def subscribed
  end
end

JS代码包含:

global.App.cable.subscriptions.create({ channel: 'NotificationsCountChannel',
  connected: () => {
    console.log('connected');
  },
  rejected: () => {
    console.log('rejected');
  },
  disconnected: () => {
    console.log('disconnected');
  },
  received: (data) => {
    console.log(data);
  },
});

客户端可以成功连接到位于'/ cable'默认路径的WebSocket。但是订阅NotificationsCountChannel并不成功。这是日志:

Started GET "/cable" for 127.0.0.1 at 2018-02-24 20:50:31 +0300
Started GET "/cable/" [WebSocket] for 127.0.0.1 at 2018-02-24 20:50:31 +0300
Successfully upgraded to WebSocket (REQUEST_METHOD: GET, HTTP_CONNECTION: Upgrade, HTTP_UPGRADE: websocket)
Subscription class not found: "NotificationsCountChannel"

此外,我无法在rails控制台中检查NotificationsCountChannel
NameError (uninitialized constant NotificationsCountChannel)

看起来Rails没有加载NotificationsCountChannel类 运行bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths'会提供不包含app/channels的路径列表。通过添加
可以修复 config.autoload_paths += %W(#{config.root}/app/services)来配置/ application.rb,但它无法解决主要问题。

我错过了什么?

1 个答案:

答案 0 :(得分:2)

事实证明答案很简单:缺乏关注 实际上channels dir位于项目的根目录中,而不是app目录中。