How to set cookies in ApplicationController?

AndrewShmig picture AndrewShmig · Jun 5, 2011 · Viewed 41k times · Source

I need to set cookies in my ApplicationController but I'm not sure how. I've tried using cookies - nothing, using ActionController::Cookies - nothing. I don't need anything more then setting and getting cookies but what I do need is to set them in ApplicationController.

EDIT:

Found the answer: request.cookies['help'] = 'yes'

Answer

amit_saxena picture amit_saxena · Jun 5, 2011

What do you mean by setting cookie in application controller? You would set cookie in browser corresponding to some controller action. If you want to set the cookie for all actions then you may consider using a before filter and apply that filter to all your controller actions.

You can set and delete cookies as shown below:

   cookies[:key] = {
       :value => 'a yummy cookie',
       :expires => 1.year.from_now,
       :domain => 'domain.com'
     }

     cookies.delete(:key, :domain => 'domain.com')

Please note that if you specify a :domain when setting a cookie, you must also specify the domain when deleting the cookie.

e.g. cookies[:user_name] = "david"