4

I can't really find the exact information that solves this quite common problem. I want to set a cookie and if it is not possible (cookies are disabled) I want to show an error page.

In my application controller I set the cookie with this:

  if (cookies[:user].blank?)
    cookies[:user] = {
      :value => (0...10).map{ ('a'..'z').to_a[rand(26)] }.join,
      :expires => 6.months.from_now,
      :domain => 'localhost'          
    }           
   end 

and then in my other controller Booking controller:

if cookies[:user].blank?
  @publish_form = false
  @no_cookies = true
end

and in the view:

   <% if @no_cookies %>
You need to enable cookies
<% end %>

Now, this doesn't really work. It will create a cookie if cookies are enabled but if cookies are disabled it will still create a "cookie" so in my Booking Controller it will have a value and thus not be blank. If the page is reloaded it will create another cookie value. It seems like it is only creating a session or something. Using request.cookie doesn't work either.

What should I use in order to create a cookie whenever a user enters the page, check if a cookie exist and show different views depending on whether a cookie exist or not?

Christoffer
  • 2,123
  • 3
  • 23
  • 50
  • This answer might help http://stackoverflow.com/questions/531393/how-to-detect-if-cookies-are-disabled-is-it-possible – lulalala Oct 25 '12 at 03:25

1 Answers1

0

I think you'll have to do a second request? Since there's no way to know in one request if you can actually set them.

Maybe you could use javascript to try to read the cookie instead?

CambridgeMike
  • 4,492
  • 1
  • 26
  • 35