按数组值顺序排列Activerecord



我有一个ActiveRecord::Relation@公式,有很多行,我想用这个序列%w[dre dre_cc cash_flow attachment_table]按范围对它们进行排序和分组

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

在Ruby on Rails 7.0中,引入了可以这样使用的in_order_of(假设scope是to列的名称(:

scopes = %w[dre dre_cc cash_flow attachment_table]
@formulas = current_user.company.formulas
ordered_formulas = @formulas.in_order_of(:scope, scopes)

当您仍然使用旧版本的Rails时,您可以通过自己构建一个复杂的订单语句来获得相同的结果:

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)

当你在应用程序中更频繁地需要这种行为时,为它创建一个助手方法或scope可能是有意义的