在保持初始排序的同时对记录数组进行两次排序
Sorting record array twice while maintaining initial sort
所以我对我的公司有以下查询
companies.where(industry: industries_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
or DESC
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)
所以我对我的公司有以下查询
companies.where(industry: industries_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)