【问题标题】:Sort products by producer name otherwise by something else in a "Rails way"按生产商名称对产品进行排序,否则以“Rails 方式”按其他方式排序
【发布时间】:2020-03-19 20:29:16
【问题描述】:

如果生产者名称为"ABC",我的客户希望通过producer name 订购产品,否则通过parameters_countimages_count 订购结果。我的架构如下所示:

Parts

id int PK

producer_id int

images_count int

parameters_count int
Producers

id int PK

lauber_id String

name string

排序的结果应该是有abc的生产者的产品排在最前面,否则显示图片数和参数数大于0的产品。

以“Rails 方式”对结果进行排序的最佳方式是什么。到目前为止,我有这个。

Part.joins('join producers on parts.producer_id = CAST(producers.lauber_id as INT)')
  .order("CASE WHEN producers.name = 'ABC' then producers.name END, images_count, parameters_count desc")

有没有更好的办法?

【问题讨论】:

  • 你使用的是什么数据库?
  • 我正在使用 Postgres

标签: ruby-on-rails postgresql activerecord rails-activerecord


【解决方案1】:

您不能在不同数量的列上对某些行进行排序。您想订购 3 样东西,其中第一个是布尔值。而且由于“false”在“true”之前,你需要颠倒顺序:

producers.name = 'ABC' desc, images_count, parameters_count desc

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2011-08-21
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    相关资源
    最近更新 更多