"Subscription class not found" ActionCable 问题

"Subscription class not found" issue with ActionCable

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

app/channels/application_cable/channel.rb

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

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
      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

app/channels/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 class。
运行 bin/rails r 'puts ActiveSupport::Dependencies.autoload_paths' 给出了不包含 app/channels 的路径列表。可以通过添加
来修复 config.autoload_paths += %W(#{config.root}/app/services) 到 config/application.rb 但它并没有解决主要问题。

我错过了什么?

原来答案很简单:缺乏关注。
实际上 channels 目录在项目的根目录中,而不是在 app 目录中。