首页 > 解决方案 > 为什么在尝试列出 rails 数组键的值时会出现 Cookie 溢出和 nil 参数?

问题描述

我在messages.html.erb 中有以下代码。

<% vars = request.query_parameters
   @templates = session[:templates]
%>

<h3>There are <%= @templates.count %> templates</h3>
<form method='post' action='http://localhost:80/text.php'>

 <select name="template">
   <% @templates.each do |t| %>
      <option name='<%=t.name %>'><%= t.name %></option>
   <% end %>
 </select>
  <br /><br />
  <input type='submit' value='Submit' />
</form>

现在,在 application_helper.rb 中,有一个方法 link_to_phone,其中我们有:

  session[:templates] = Template.all
  link_to(h(phone), message_path(phone: phone, id: contact.id, page: 'contacts'), title: phone)

message_path 将我们带到messages.html.erb。

如果该部分(我省略了电话,ID和页面字段,因为它们在这里不起作用):

 <select name="template">
   <% @templates.each do |t| %>
      <option name='<%=t.name %>'><%= t.name %></option>
   <% end %>

从messages.html.erb中省略,我得到这样的声明,在我的例子中,link_to_phone定义在会话中存储了3个模板。如果该部分包含在代码中,那么我会得到一个 Cookie 溢出。据我所知,我没有使用 cookie,而是认为我正在使用会话。我的 view/template/index.html.erb 中有另一个与此非常相似的语句,其中我循环遍历 @templates 并显示名称、味精和主题,使用完全相同的想法,除了放置单独的模板名称味精,并没有问题地进入一张桌子。

我在这里错过了什么导致这个“Cookie”问题?

标签: htmlruby-on-railssession-variables

解决方案


会话实际上是 cookie,但信息存储在服务器端,并带有会话 id 的 cookie 传递给用户的浏览器。整个 cookie 的大小限制为 4KB,包括名称、值、到期日期。

但是 Rails 默认将 session 信息存储在 cookie_store 中,你可以通过更改 session_store 来解决这个问题,例如可以使用 active_record_store。

请参阅:rails 应用程序中的 Cookie 溢出?


推荐阅读