按数组值序列排序 Activerecord
Order Activerecord by array values sequence
我有一个包含很多行的 ActiveRecord::Relation @formulas,我想使用此序列 %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
可能是有意义的。
我有一个包含很多行的 ActiveRecord::Relation @formulas,我想使用此序列 %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
可能是有意义的。