如何根据用户的 ip 地址显示产品的价格

How can I show product's price due to user's ip address

我正在建立一个电子商务网站,我想根据用户的 IP 地址显示产品的价格。为了获取 IP,我使用此代码:current_user.current_sign_in_ip。为了获取 IP 地址的区域,我使用了这个:Geocoder.search(current_user.current_sign_in_ip)。我的 Product 模型通过 table ProductCurrency 连接到 Currency 模型,我在其中存储 product_idcurrency_id 和 '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

所以,我的 Product 可以有多种货币(欧元、美元)和价格(100 欧元、150 美元)。对于 Currency 模型,我有一个名为 CurrencyRegion 的联接 table,我在其中存储 currency_idregion_id。还有一个相关的模型叫做 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

那么,如果用户 IP 地址来自美国,我该如何做才能以美元显示产品价格?先谢谢了。

请尝试以下代码:

region = Geocoder.search(current_user.current_sign_in_ip)
price  = ProductCurrency.
           joins(currency: :regions).
           where('regions.name = ?', region).
           pluck('product_currencies.price').
           first