我有一個 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 = ...
uj5u.com熱心網友回復:
在 Ruby on Rails 7.0in_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當您在應用程式中更頻繁地需要這種行為時,創建一個輔助方法或為它創建一個輔助方法可能是有意義的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/445022.html
下一篇:asdf與bundler的區別
