Reputation: 889
I would like to store user selected value on view on the cookies in rails.
So there would be 2 links as currencies, such as; euros and dollars. When user selects / clicks one of the links, it should update cookies[:curr]
. Then the action should refresh the page with redirect_to :back
My problem is, I would like to add this option to footer. So user can access to this option anywhere on the web-site. But how can I change cookies[:curr]
value when user selects on home page or any other controller?
I put below function to application controller to check the value of the cookies[:curr]
def return_currency
if cookies[:curr].blank? || cookies[:curr].nil?
'€' #default
elsif cookies[:curr] == 'USD'
'$'
end
end
So here, I can check the value but, I could not figure it out how to assign an user selected value. Should it be a form_for
? But then I can only send data to 1 controller, but I want user to access to any action as it will be at the footer.
Thank you
Upvotes: 0
Views: 493
Reputation: 12213
A form might be sensible, as it would allow you to use a select, radio buttons or another field type to update the currency.
However, you could achieve this very simply by using a couple of link, such as the following.
In the view:
<%= link_to '€', your_currency_update_path(curr: '€') %>
In the controller:
def your_currency_update_action
cookies[:curr] = params[:curr]
redirect_to :back
end
Clicking this link will hit the controller passing the params[:curr]
and redirect the user where they came from.
Or using a form like this:
<%= form_tag(your_currency_update_path, method: :post) do %>
<%= select_tag :curr, options_for_select([['€'], ['$']) %>
<%= submit_tag "Update Currency" %>
<% end %>
Finally, you could do away with the form's submit button by having it auto submit on change using the following:
<%= select_tag :curr, options_for_select([['€'], ['$']) %>, onchange: "this.form.submit();" %>
It doesn't matter which page this link / form is submitted from as it will always hit the controller action you choose to handle this, before redirecting back.
Hope that helps - let me know how you get on or if you have any questions.
Upvotes: 3