场景:
产品以用户指定的货币显示,而每个产品都有自己的原始货币(可以与用户指定的相同,也可以是任何其他货币)
用户想要搜索以其用户指定的货币(假设为美元)具有特定价格范围 (10 - 100) 的产品
我正在使用 postgres 和 Rails。每个产品都有一个price_amount和货币为原始货币。
问题 由于每种产品可以采用任何货币,因此我需要将所有产品标准化为用户指定的货币,以便我可以看到哪些产品在范围内。
我有每对支持的货币的汇率。但是查询会非常复杂,所以我想知道是否有更高效的方法?
currencies.map do |currency|
rate = ex_rate(user_specific_currency, currency)
query = [query , "products.price * #{rate} <= user_max AND products.price * #{rate} >= user_min AND products.currency = '#{currency}'"].join(" OR ")
end
Product.where(query)
最佳答案
您可以使用SQL CASE对于它:
SELECT price, currency,
CASE WHEN currency='USD' THEN price * 1
WHEN currency='RUB' THEN price * 65
ELSE price
END as final_price
FROM products
WHERE final_price BETWEEN 10 AND 100
CASE clauses can be used wherever an expression is valid. Each condition is an expression that returns a boolean result. If the condition's result is true, the value of the CASE expression is the result that follows the condition, and the remainder of the CASE expression is not processed. If the condition's result is not true, any subsequent WHEN clauses are examined in the same manner. If no WHEN condition yields true, the value of the CASE expression is the result of the ELSE clause. If the ELSE clause is omitted and no condition is true, the result is null.
Rails 版本:
Product.select("price, currency, CASE
WHEN currency='USD' THEN price * 1
WHEN currency='RUB' THEN price * 65
ELSE price END as final_price")
.where("final_price BETWEEN ? AND ?", 10, 100)
关于ruby-on-rails - 搜索给定不同货币价格范围的型号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32627119/