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.pe开发者_开发问答rmanent.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.
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])
In your save_user_id_cookie
:
def save_user_id_cookie
cookies.permanent.signed[:user_id] = @user_id # may be @user.id?
puts 'saved cookie'
end
@user_id
is nil. I think you should use @user.id
instead.
Try this:
@current_user = @current_user || User.find(*cookies.signed[:user_id])
Notice the * before the cookies.
and yes, as @nash
pointed out, that user_id
should be actually user.id
.
I didn't bother to look there for errors, as you said that you could see the cookie on your machine.
精彩评论