user2784630
user2784630

Reputation: 806

How to set cookie so it appears back on form?

I have a field called params[:search_loc] that's for a public user where they can put in there address and get results near there. I'm trying to save it in a cookie so when a public user leaves a page they can come back and have the same address until they change it. Here is the view and the controller. This is what I tried.

Controller

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

View

<% 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 %>

Right now it doesn't set the cookie for the address but it is saved in the browser. How can I get it to show in the search_loc field after I leave to another page?

Upvotes: 0

Views: 61

Answers (1)

Santhosh
Santhosh

Reputation: 29174

You are setting a cookie, but not accessing it. Try this

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

Upvotes: 1

Related Questions