Ruby on Rails - Cookie值仅在刷新时显示 [英] Ruby on Rails - Cookie value displays only on refresh

查看:91
本文介绍了Ruby on Rails - Cookie值仅在刷新时显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下拉菜单,在我的一个视图中,允许我选择页面上的图像数量。我想记住在该页面上的选择,所以当用户回来时,显示的图像数量是他们上次选择的。



为了实现这一点,我如下所示,在控制器中设置cookie值:


 如果cookie [:per_page] .blank? 
cookies [:per_page] =50#这是新用户的默认值,并且现有用户删除cookie
else
cookie [:per_page] = params [:noofimages_perpage ] .to_s#这是在下拉菜单中选择的值
end
@pp = cookies [:per_page]
#进一步处理cookie值
end


但我没有得到cookies [:per_page]中的值。



要检查Cookie中的值,我已将此行添加到我的视图中

 <%= @pp%> 

,并且视图只在刷新后显示值。



A视图的一部分在这里

 < select name =noofimages_perpageonchange =call the controller > 
< option value =50> 50< / option>
< option value =100> 100< / option>
< option value =150> 150< / option>
< / select>

阅读了几篇帖子和文章后,我明白,回传。



有关如何处理这个问题或有关工作的指示?



解决方案

>控制器中没有设置cookie,而是在控制器的响应中(因为它是浏览器的东西)。这意味着在页面呈现时设置cookie。您无法在此页面上访问它,但在下一页或刷新。



考虑重定向到同一页面


I have a drop down in one of my views, allowing me to select the number of images on the page. I want to remember the selection on that page, so when the user comes back, the number of images displayed are what they selected last time around.

To achieve this I am setting the cookie value from within the controller like this

if cookies[:per_page].blank?
    cookies[:per_page] = "50" # this is the default value for a new user and incase the existing user deletes the cookie
 else
    cookies[:per_page] = params[:noofimages_perpage].to_s # this is the value selected in the drop down   
 end
     @pp = cookies[:per_page] 
     # further processing with the cookie value here
end  

But I don't get the value in cookies[:per_page].

For checking the value in the cookie, I added this line to my view

<%= @pp %>  

and the view displays the value only after a refresh.

A Part of the view is here

<select name="noofimages_perpage" onchange="call the controller">
 <option value="50">50</option> 
 <option value="100">100</option>
 <option value="150">150</option>
</select>

After reading a few posts and articles, I understand that cookie write won't be available until the subsequent postback.

Some pointers on how to handle this or a work around please?

As far as possible I want to achieve this without touching the database.

Many Thanks

解决方案

A cookie isn't set in the controller but in the response of the controller (because it's a browser thing). that means the cookie is set when the page is rendered. you cant access it on this page but on the next page or refresh.

consider a redirect (to the same page) as a workaround

这篇关于Ruby on Rails - Cookie值仅在刷新时显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆