如何将 rails group_by class 方法重写为作用域
How to rewrite rails group_by class method as scope
我想将我的 class 方法重写为范围。
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
你不能把它写成范围。 Rails 中的范围作用于 ActiveRecord::Relation
对象,并且应该生成 SQL
对数据库的 运行 查询。
但是 group_by
方法是在 array
上从数据库接收到数据后调用的。
您总是必须先从数据库加载数据,然后才能将其与 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
强制作用域实际从数据库加载数据和 returns 一个数组。
我想将我的 class 方法重写为范围。
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
你不能把它写成范围。 Rails 中的范围作用于 ActiveRecord::Relation
对象,并且应该生成 SQL
对数据库的 运行 查询。
但是 group_by
方法是在 array
上从数据库接收到数据后调用的。
您总是必须先从数据库加载数据,然后才能将其与 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
强制作用域实际从数据库加载数据和 returns 一个数组。