# How to read cookies

**URL:** <https://www.ruby-forum.com/t/how-to-read-cookies/84809>\
**Category:** Rails\
**Created:** [February 7, 2007, 9:48pm UTC](https://www.ruby-forum.com/t/how-to-read-cookies/84809 "2007-02-07T21:48:24Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![jason](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/dc4da7/32.png) [@jason](https://www.ruby-forum.com/u/jason)\
**Post date:** [February 7, 2007, 9:48pm UTC](https://www.ruby-forum.com/t/how-to-read-cookies/84809/1 "2007-02-07T21:48:24Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![jason](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/dc4da7/32.png) [@jason](https://www.ruby-forum.com/u/jason)\
**Post date:** [February 7, 2007, 10:00pm UTC](https://www.ruby-forum.com/t/how-to-read-cookies/84809/2 "2007-02-07T22:00:04Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![jason](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/dc4da7/32.png) [@jason](https://www.ruby-forum.com/u/jason)\
**Post date:** [February 7, 2007, 10:03pm UTC](https://www.ruby-forum.com/t/how-to-read-cookies/84809/3 "2007-02-07T22:03:07Z")

</div>

Yes, that works.

Thank you very much!

---

<div class="post-metadata">

**Author:** ![jason](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/dc4da7/32.png) [@jason](https://www.ruby-forum.com/u/jason)\
**Post date:** [February 7, 2007, 10:03pm UTC](https://www.ruby-forum.com/t/how-to-read-cookies/84809/4 "2007-02-07T22:03:42Z")

</div>

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.
