Home > Net >  Order Activerecord by array values sequence
Order Activerecord by array values sequence

Time:03-16

I have a ActiveRecord::Relation @formulas with many rows, i want to order and group them by scope with this sequence %w[dre dre_cc cash_flow attachment_table]

@formulas = current_user.company.formulas
scopes = %w[dre dre_cc cash_flow attachment_table]
ordered_formulas = ...

CodePudding user response:

In Ruby on Rails 7.0 in_order_of was introduced that can be used like this (assuming that scope is the name of to column):

scopes = %w[dre dre_cc cash_flow attachment_table]

@formulas = current_user.company.formulas
ordered_formulas = @formulas.in_order_of(:scope, scopes)

When you are still on an older version of Rails then you can get the same result by building a complex order statement by yourself:

scopes = %w[dre dre_cc cash_flow attachment_table]

@formulas = current_user.company.formulas

order_clause = "CASE  scope "
scopes.each_with_index do |scope, index|
  order_clause << sanitize_sql_array(["WHEN ? THEN ? ", scope, index])
end
order_clause << sanitize_sql_array(["ELSE ? END", scopes.length])

ordered_formulas = @formulas.order(order_clause)

When you need this behavior more often in your app then it might make sense to create a helper method or scope for it.

  • Related