Search code examples
rubyruby-on-rails-3cookieshelpermethods

How do I work with Rails 3 cookies and helpers?


I created a user and stored the id in a permanent cookie:

def save_user_id_cookie
  cookies.permanent.signed[:user_id] = @user_id
end

Here is a link.

and then try to access it:

helper_method :current_user

private
def current_user
  @current_user = @current_user || User.find(cookies.signed[:user_id])
end

Here is a link.

I see the cookie on my machine but when I try to load the homepage I get:

Couldn't find User without an ID

app/controllers/application_controller.rb:8:in `current_user'

The controller is here.


Solution

  • Believe this line

    @current_user = @current_user || User.find(cookies.signed[:user_id])
    

    should be

    @current_user = @current_user || User.find(cookies[:user_id])
    

    *side note: for little less code you can try assigning like

    @current_user ||= User.find(cookies[:user_id])