I'm using ActionCable (ruby on rails v6.1.4) and I'm trying to access my cookies with the Connection class, but I keep getting the "undefined local variable or method `cookies' for ApplicationCable::Connection:Class" error.
My cookies work without an issue in development and production. I only experience this when working with ActionCable.
I've followed the instructions of this answer, but I still get the error.
Here is the 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
In case there's an issue with my cable.yml
, here is the file:
development:
adapter: async
test:
adapter: test
production:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
channel_prefix: backend_production
CodePudding user response:
I found the solution.
I needed an identification index, along with a connect and a disconnect method. You're able to access cookies within those methods.
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