Forum: Ruby on Rails How to read cookies

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
74bd868b70df3590bf94cf7abe563ec4?d=identicon&s=25 Jason (Guest)
on 2007-02-07 21:48
I'm having trouble setting/reading cookies in Rails.

I want a cookie that shows the user name in a layout.

Here's what I have in my login controller:

 session[:user_id] =
        cookies[:user_role] = user.role
        cookies[:user_name] = { :value =>,
                                :expires => 30.days.from_now }

Then, here's what I have in my layout view:

 Logged in as:<br />
        <% usr_name = cookies[:user_name]%>
        <%= render(:text => "#{usr_name}") %>

What am I doing wrong?

72eb65fa089082d3bd8b38a5596ad331?d=identicon&s=25 Keynan Pratt (keynan)
on 2007-02-07 22:00
assign the cookie to a @var in the controller not the view
74bd868b70df3590bf94cf7abe563ec4?d=identicon&s=25 Jason (Guest)
on 2007-02-07 22:03
Yes, that works.

Thank you very much!
F01c3ff32fee35d911e81c172a005012?d=identicon&s=25 Tom Fakes (Guest)
on 2007-02-07 22:03
(Received via mailing list)
It's not obvious, but the cookies you are setting in the controller
are in response object, but the ones you are reading in the view are
in the request object.

What this means is you can't easily read the cookies you set in the
current request (but your code will work for subsequent requests)

To do what you are trying to do, I would not use cookies.  Use the
session[:user_id] value to reload a @current_user object on every
request using a before_filter, and then you can use that to display
the info you want.
This topic is locked and can not be replied to.