I'm beginner in RoR. Just creating smth like internet shop, I need make convert price at another currencies. For that i have service class
@product_decorator = Product.includes(:category).map{|product| ProductDecorator.new(product)}
Also i has table in db with actual courses
create_table :product_wrappers do |t|
t.decimal :euro
t.decimal :rubles
end
In view it works good if i manually change product's price method at euro/rubles, but i need do it at link_to methods with new params like eur/rub, I'm rly stuck at that i need create method in store_controller
Routes
put '/set_currency', to: 'store#set_currency'
View
<%= link_to "USD", set_currency_path(:currency => :usd), class: "btn btn-outline-secondary" %>
<%= link_to "RUB", set_currency_path(:currency => :rub) ,class: "btn btn-outline-secondary" %>
<%= link_to "EUR", set_currency_path(:currency => :eur), class: "btn btn-outline-secondary" %>
CodePudding user response:
Just as ideas
To build URL with currency as query param use such helper
<%= link_to "My product", product_path(product, currency: :eur) %>
It will generate such HTML
<a href="/products/1?currency=eur">My product</a>
In your controller, probably ApplicationController
before_action :set_current_currency
def set_current_currency
@current_currency = params[:currency] || 'eur'
end
And to show price in selected currency in views something like this
product.public_send(@current_currency)
Also may be it's a good idea to save selected currency in session or use user profile
def set_current_currency
currency =
if params[:currency]
params[:currency]
elsif session[:currency]
session[:currency]
elsif current_user
current_user.preferred_currency
end
session[:currency] =
if currencies.include?(currency)
currency
else
default_currency
end
end
And than use session[:currency]
in your views instead of @current_currency