How to read cookies


#1

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] = user.id
cookies[:user_role] = user.role
cookies[:user_name] = { :value => user.name,
:expires => 30.days.from_now }

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

Logged in as:

<% usr_name = cookies[:user_name]%>
<%= render(:text => “#{usr_name}”) %>

What am I doing wrong?

Thanks!


#2

assign the cookie to a @var in the controller not the view


#3

Yes, that works.

Thank you very much!


#4

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.