代码之家  ›  专栏  ›  技术社区  ›  Anand Shah

Ruby on Rails-cookie值仅在刷新时显示

  •  2
  • Anand Shah  · 技术社区  · 16 年前

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

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

    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  
    

    但是我没有得到cookies中的值[每页]。

    为了检查cookie中的值,我将此行添加到视图中

    <%= @pp %>  
    

    视图仅在刷新后显示该值。

    这里有一部分风景

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

    在阅读了一些帖子和文章之后,我了解到在随后的回发之前,cookie的编写是不可用的。

    关于如何处理这件事或解决这件事的一些建议?

    我希望尽可能在不接触数据库的情况下实现这一点。

    多谢

    2 回复  |  直到 16 年前
        1
  •  0
  •   Martin Labuschin    16 年前

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

    考虑将重定向(到同一页)作为解决方法

        2
  •  0
  •   Mike Sutton    16 年前

    尝试

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