ruby-on-rails 轨道根据较低的值排列2列

yrwegjxp  于 7个月前  发布在  Ruby
关注(0)|答案(2)|浏览(77)

我不知道如何恰当地表达这个问题。
如何编写order()以使我的产品按(discounted_price || price) DESC排序?
| ID|价格|折扣价格|
| --|--|--|
| 1 | 1 |null|
| 2 | 3 |null|
| 3 | 4 | 2 |
应该返回id 1,3,2
你如何正确表达这个问题?

pobjuy32

pobjuy321#

使用COALESCE:

Product.order(
  # COALESCE(discounted_price, price) DESC
  Product.arel_table.then { |p| p.coalesce(p[:discounted_price], p[:price]) }.desc
)

字符串
这个函数在RDBMS中是相当标准化的,它返回第一个非空参数。

1yjd4xko

1yjd4xko2#

你应该能够做类似于:order(discounted_price: :desc, price: :desc)

相关问题