ruby-on-rails - 搜索给定不同货币价格范围的型号

标签 ruby-on-rails postgresql ruby-on-rails-4

场景:

产品以用户指定的货币显示,而每个产品都有自己的原始货币(可以与用户指定的相同,也可以是任何其他货币)

用户想要搜索以其用户指定的货币(假设为美元)具有特定价格范围 (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/

相关文章:

ruby-on-rails - Rails 跛脚过滤器?

ruby-on-rails - Ruby On Rails - 当 gem 在其 Gemfile HTTP 源中使用时,中间人攻击?

ruby-on-rails - 专业 Rails 托管服务的优势和缺陷是什么?

postgresql - pg_upgradecluster 花费太多时间(165GB 数据库大约需要 8 小时)有什么解决方法吗?

postgresql - 在 postgresql 查询的 IN 子句中使用变量

ruby-on-rails - Rails 在另一个窗体中渲染窗体的一部分

oracle - 为什么 PostgreSQL 允许没有 order by expression 的 frame 子句?

ruby-on-rails - 生成迷你测试 :spec test for an existing controller for functional testing

javascript - 在版本 4.4.6 中禁用 ckeditor 上下文菜单

mysql - 从数据库中选择多个计数