Reputation: 13363
I'm working on a form that should allow users to update a session variable called session[:city]
that tracks their location. The variable doesn't need to be saved in the database cause it's kind of a throwaway; it only needs to exist while the user is on the site.
session[:city]
is used in several places throughout the site, so I've placed the following method in the Application Controller:
class ApplicationController < ActionController::Base
before_filter :set_city
def set_city
unless session[:city].present?
session[:city] = request.location.city
end
if params[:city].present?
session[:city] = params[:city]
end
end
end
That part works correctly, and I'm able to call the variable throughout the site.
The issue I'm having is in updating the variable by a form. The only action I need it to do is update the variable, but it's not responding. I know I'm missing something here, but after trying a bunch of things I'm a bit stumped. This is my basic form currently:
<%= form_tag do %>
<%= text_field_tag :city, params[:city] %>
<%= submit_tag %>
<% end %>
Edited to working code
Upvotes: 1
Views: 602
Reputation: 13363
The conditions needed to be split into 2 statements: an unless to set the session[:city] and an if to check if any params were being passed.
class ApplicationController < ActionController::Base
before_filter :set_city
def set_city
unless session[:city].present?
session[:city] = request.location.city
end
if params[:city].present?
session[:city] = params[:city]
end
end
end
And the working form:
<%= form_tag root_path do %>
<%= text_field_tag :city, params[:city], :placeholder => "#{session[:city]}: Change City" %>
<% end %>
Upvotes: 1
Reputation: 5111
You can try something like this:-
<%= form_tag do %>
<%= text_field_tag :person, :city, :name => "city" %>
<%= submit_tag %>
<% end %>
class ApplicationController < ActionController::Base
before_filter :set_city
def set_city
unless session[:city].present?
session[:city] = params[:city] || request.location.city
end
end
end
Upvotes: 2
Reputation: 29349
This will not work in production like environment where you have multiple worker process to serve the requests(unicorn or passenger). Each process will have its own memory. If the value is changed during a request processed by one worker process, other processes will not have the updated value.
You should be using session to store this information.
Upvotes: 2