Wednesday, October 10, 2007

Rails Cookies in a view

I never really found an answer to this anywhere, but it looks like Rails does not allow access to the cookies object in the view. You have to access it as @cookies. I suspect this is so you won't set a cookie in the view, but I don't really know why that's an issue. I was trying to access it to see what was in it while testing.

Also - it appears the default behavior of the cookie expires property is 'now', not 'never' as stated in the DHH's rails book, (Feb 2006).

So - to get the "remember me" cookie to act as I wanted - I set the expires to be far off in the future. Good enough for my purposes.

cookies[:user_id] = {:value =>, :expires => 1.years.from_now }

I don't know if there is a security issue with this at this point. Storing the users ID locally and using only that to sign in sounds like a security problem. I'll do something to hide this if so.

1 comment:

  1. Anonymous7:21 AM

    Did you ever discover more about this? I am referring to a cookie in a view and getting inconsistent crazy results. Of course, it worked perfectly on my dev box and failed every time in staging.

    Basically, it feels like cookies['name'] isn't always populated while the view is rendering.