【问题标题】:How to rewrite rails group_by class method as scope如何将rails group_by类方法重写为范围
【发布时间】:2016-04-03 19:32:54
【问题描述】:

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

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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 scope refactoring


    【解决方案1】:

    你不能把它写成一个作用域。 Rails 中的作用域作用于ActiveRecord::Relation 对象,并且应该生成针对数据库运行的SQL 查询。

    但是在从数据库接收到数据后,array 上调用了group_by 方法。

    您始终必须先从数据库加载数据,然后才能将其与group_by 分组。

    您可以在 Array 上编写自己的 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,它强制作用域从数据库中实际加载数据并返回一个数组。

    【讨论】:

      猜你喜欢
      • 2014-11-20
      • 1970-01-01
      • 2011-08-19
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      相关资源
      最近更新 更多