如何将 rails group_by 类方法重写为作用域 [英] How to rewrite rails group_by class method as scope

查看:36
本文介绍了如何将 rails group_by 类方法重写为作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将我的类方法重写为作用域.

I would like to rewrite my class method as a scope.

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 查询.

You cannot write this as a scope. Scopes in Rails act on ActiveRecord::Relation objects and are supposed to generate SQL queries that run against the database.

但是group_by 方法是在从数据库接收到数据后在array 上调用的.

But the group_by method is called on the array after the data was received from the database.

您总是必须先从数据库加载数据,然后才能使用 group_by 对其进行分组.

You will always have to load the data from the database first, before you can group it with group_by.

您可以在 Array 上编写自己的 nested_group_by 方法:

You could write your own nested_group_by method on Array:

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 强制作用域从数据库中实际加载数据并返回一个数组.

Note the all that force the scope to actually load the data from the database and returns an array.

这篇关于如何将 rails group_by 类方法重写为作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆