ApplicationCable::Connection:Class 的未定义局部变量或方法“cookies”

undefined local variable or method `cookies' for ApplicationCable::Connection:Class

我正在使用 ActionCable(ruby on rails v6.1.4)并且我正在尝试使用连接 class 访问我的 cookie,但我一直收到“ ApplicationCable::Connection:Class 错误的未定义局部变量或方法“cookies”。

我的 cookie 在开发和生产中没有问题。我只有在使用 ActionCable 时才会遇到这种情况。

我已按照 的说明进行操作,但仍然出现错误。

这里是 class:

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    include ActionController::Cookies

    if cookies.signed[:user_id]
      puts "User found"
    else
      puts "User not found"
    end
  end
end

万一我的 cable.yml 有问题,这里是文件:

development:
  adapter: async

test:
  adapter: test

production:
  adapter: redis
  url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
  channel_prefix: backend_production

我找到了solution

我需要一个识别索引,以及一个连接和断开连接的方法。 您可以在这些方法中访问 c​​ookie。

module ApplicationCable
  class Connection < ActionCable::Connection::Base
    identified_by :current_user #identification index

    def connect
      self.current_user = User.find_by(id: cookies.encrypted['_cookie_name']['user_id'])
    end

    def disconnect
      # Any cleanup work needed when the cable connection is cut.
    end
  end
end