Reputation:
In my application in one of my views, I add a Cookie
from my Controller
and based on this Cookie
, I set a value to my variable (which will be used in my view).
class SomeController < ApplicationController
def a_action
if params[:utm] == 'a'
cookies[:user_cookie] = {value: 'a', expires: 1.day.from_now}
else
cookies[:user_cookie] = {value: 'b', expires: 1.day.from_now}
end
if cookies[:user_cookie] == 'a'
@variable = 'a'
else
@variable = 'b'
end
end
In my view a_action#some
, I'm doing:
%h1= @variable
When user is coming to a_action#some
view, cookies[:user_cookie]
is set to user's browser cookie, but my view or controller doesn't read Cookie
value until next refresh. So @variable
in my view becomes wrong value/no value at all.
Is it possible to read Cookie
after page is loaded so my @variable
always has a value and don't need to wait for next refresh?
Upvotes: 0
Views: 1989
Reputation: 13521
Cookies are a client side feature. You server can only read cookies when there is a request, i.e in your controller action.
The only way to read a cookie after the page has loaded is with Javascript: document.cookie
https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
http://clubmate.fi/setting-and-reading-cookies-with-javascript/
Upvotes: 1