代码之家  ›  专栏  ›  技术社区  ›  nfm

如何在ActiveRecord类方法中使用“map”方法?

  •  1
  • nfm  · 技术社区  · 14 年前

    我的Ruby语法不太确定。

    我想定义一个可以这样调用的方法: client.invoices.average_turnaround average_turnaround 方法需要使用ActiveRecord对象的集合。

    class Invoice < ActiveRecord::Base
      ...
      def self.average_turnaround
        return self.map(&:turnaround).inject(:+) / self.count
      end
    end
    

    所以我试着找出每张发票周转时间的总和,然后除以发票的总数。

    map 为定义的方法 Class . 我在期待 self Array .

    如何编写一个方法来处理 Invoices 功能?我哪里出错了?

    2 回复  |  直到 14 年前
        1
  •  4
  •   Teoulas    14 年前

    您定义了一个类方法,该方法在类本身上被调用。你需要的是一个 association extension

    class Client < ActiveRecord::Base
      has_many :invoices do
        def average_turnaround
          return map(&:turnaround).inject(:+) / count
        end    
      end
    
        2
  •  7
  •   kequc    10 年前

    如果要在类方法中使用map,而不是通过关联扩展。例如,如果打电话给 Invoice.average_turnaround 直接或间接 Invoice.where(x: y).average_turnaround . 地点 all. map .

    class Invoice < ActiveRecord::Base
      ...
      def self.average_turnaround
        all.map(&:turnaround).inject(:+) / all.count
      end
    end
    

    average_turnaround