如何设置cookie,使其显示在表单上?

时间:2014-06-03 15:39:53

标签: ruby-on-rails ruby cookies ruby-on-rails-4

我有一个名为params[:search_loc]的字段,用于公共用户,他们可以在那里放置地址并在那附近获得结果。我正在尝试将其保存在cookie中,因此当公共用户离开页面时,他们可以返回并拥有相同的地址,直到他们更改它为止。这是视图和控制器。这就是我的尝试。

控制器

def index
  @dad = Dad.find(params[:dad_id])
  cookies[:search_loc] = params[:search_loc]
  if user_signed_in?
   near = Mom.near(@user_location, 500, select: "kids.*")
  elsif cookies[:search_loc].present?
   near = Mom.near(cookies[:search_loc], 500, select: "kids.*")
  elsif params[:search_loc].present?
   near = Mom.near(params[:search_loc], 500, select: "kids.*")
  end
end

查看

<% if params[:search_loc].blank? %>
   <%= form_tag dad_kids_path(@dad), method: :get do %>
      <%= text_field_tag :search_loc, params[:search_loc] %>
         <%= button_tag(type: 'submit') do %>
           Save
         <% end %>
      <% end %>
   <% end %>
<% end %>

现在它没有为地址设置cookie,但它保存在浏览器中。如何在离开另一页后将其显示在search_loc字段中?

1 个答案:

答案 0 :(得分:1)

您正在设置Cookie,但不会访问它。试试这个

elsif params[:search_loc].present?
  cookies[:search_loc] = params[:search_loc]
  near = Mom.near(params[:search_loc], 500, select: "kids.*")
elsif cookies[:search_loc].present?
  near = Mom.near(cookies[:search_loc], 500, select: "kids.*")
end