2017-08-28 138 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

謝謝,這似乎解決方案,我需要 –

相關問題