2017-08-28 36 views
0

我正在构建电子商务网站,并且我想根据用户的IP地址显示产品价格。为了获得IP,我使用这个代码:current_user.current_sign_in_ip。要获取IP地址的区域,我使用:Geocoder.search(current_user.current_sign_in_ip)。我的Product型号通过表ProductCurrency连接到Currency型号,其中我存储product_idcurrency_id和'价格'。如何根据用户的IP地址显示产品价格

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的连接表,其中我存储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地址是来自美国?谢谢你。

回答

0

请尝试以下代码:

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

谢谢,这似乎解决方案,我需要 –

相关问题