0

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 = ...
3
  • Are you using postgres or mysl? Commented Mar 10, 2022 at 3:44
  • i'm using postgres Commented Mar 10, 2022 at 4:04
  • Can you please mention expected output as well? Question is non expeditionary! Commented Mar 10, 2022 at 5:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

and there is an alternative for an older ruby version?
@Joana I updated my answer to address your question.
it returns undefined method `sanitize_sql_array' for
sanitize_sql_array is only available in the context of ActiveRecord. This code needs to be used in a scope or class method of an ActiveRecord class. or you have to call the sanitize_sql_array method on a class, for example like this: Formula.sanitize_sql_array(...) (assuming that you have an ActiveRecord model called Formular)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.