ruby-on-rails - 对记录数组进行两次排序,同时保持初始排序

标签 ruby-on-rails ruby ruby-on-rails-5

所以我对我的公司有以下查询 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 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)

关于ruby-on-rails - 对记录数组进行两次排序,同时保持初始排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66101791/

相关文章:

ruby - 使用 Ruby 查找给定编码字符串的组合

ruby-on-rails - 如何使用 RSpec & Rails 4 测试子域约束

ruby-on-rails - 运行 rails server 时出现 SegFault

ruby-on-rails - 如何使用 Rails Form 和 Role Model Gem 添加多个角色

ruby-on-rails - 如何使用不同的列作为外键强制 has_many 关联

ruby-on-rails - Bundler 2 未安装在 docker 中

ruby-on-rails-5 - Ruby on Rails 5 Action 电缆 : stream for current model instance (URL-based subscriptions)

javascript - rails Assets 管道 javascript "SyntaxError: Unexpected token export"

ruby-on-rails - Bundle exec 修复了 Rake 错误,但部署不起作用

javascript - GOOGLE CHARTS 使用实现折线图作为动态数组对象循环