2016-04-03 26 views
1

我想將我的類方法重寫爲作用域。如何將rails group_by類方法重寫爲作用域

class Team 

def self.grouped 
    self.all.group_by { |e| e.type }.map { |k, v| { k => v.group_by { |e| e.sub_type } } } 
end 

end 

我該如何寫作範圍?

class Team 

# scope :grouped ?? 

end 

回答

1

你不能把它寫成範圍。 Rails中的作用域對ActiveRecord::Relation對象起作用,應該生成SQL針對數據庫運行的查詢。

但是在從數據庫接收到數據後,在array上調用group_by方法。

您必須首先從數據庫加載數據,然後才能將其與group_by分組。

你可以在陣列編寫自己的nested_group_by方法:

class Array 
    def nested_grouped_by(group_1, group_2) 
    group_by { |e| e.send(group_1) }. 
     map { |k, v| { k => v.group_by { |e| e.send(group_2) } } } 
    end 
end 

這可能是這樣使用:

Team.all.nested_grouped_by(:type, :subtype) 

注意,迫使範圍實際上all從數據庫加載數據並返回一個數組。