所以我对我的公司有以下查询
companies.where(行业:industry_queried)
我想对它们进行排序,以便返回的第一条记录是 plan_id == 3 的记录,然后是 2,然后是 1。(降序)
但是,我还想分别排列这 4 个部分,以便它们按名称的字母顺序排序。
我将如何在 Rails 5 中执行此操作?
最佳答案
活跃Record Query Interface guide ,为我们提供以下有关订购记录的信息。
4 Ordering
To retrieve records from the database in a specific order, you can use the
order
method.For example, if you're getting a set of records and want to order them in ascending order by the
created_at
field in your table:Customer.order(:created_at) # OR Customer.order("created_at")
You could specify
ASC
orDESC
as well:Customer.order(created_at: :desc) # OR Customer.order(created_at: :asc) # OR Customer.order("created_at DESC") # OR Customer.order("created_at ASC")
Or ordering by multiple fields:
Customer.order(orders_count: :asc, created_at: :desc) # OR Customer.order(:orders_count, created_at: :desc) # OR Customer.order("orders_count ASC, created_at DESC") # OR Customer.order("orders_count ASC", "created_at DESC")
将此应用于您的问题,您最终会得到:
companies.where(industry: industries_queried).order(plan_id: :desc, name: :asc)
关于ruby-on-rails - 对记录数组进行两次排序,同时保持初始排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66101791/