I'm building an e-commerce site, and I want to show product's price due to user's IP address. For getting the IP I use this code: current_user.current_sign_in_ip. To get the region of the IP address, I use this: Geocoder.search(current_user.current_sign_in_ip). My Product model is connected to a Currency model through a table ProductCurrency, where I store product_id, currency_id and 'price'.
class Product < ApplicationRecord
belongs_to :category
has_many :variants
has_many :product_currencies
has_many :currencies, through: :product_currencies
accepts_nested_attributes_for :product_currencies, allow_destroy: true
accepts_nested_attributes_for :variants, allow_destroy: true, reject_if: :all_blank
end
class Currency < ApplicationRecord
has_many :product_currencies, dependent: :destroy
has_many :products, through: :product_currencies
has_many :currency_regions
has_many :regions, through: :currency_regions
end
class ProductCurrency < ApplicationRecord
belongs_to :product
belongs_to :currency
end
So, my Product can have several currencies (EUR, USD) and prices (100 EUR, 150 USD). For a Currency model, I have a joining table called CurrencyRegion, where I store currency_id and region_id. And a related model called Region
class Region < ApplicationRecord
has_many :currency_regions
has_many :currencies, through: :currency_regions
end
class CurrencyRegion < ApplicationRecord
belongs_to :currency
belongs_to :region
end
So, what can I do to display product's price in USD if users IP address is from USA? Thanks ahead.
Please try below code: