Rails在模型中总结相关记录

时间:2014-12-04 20:06:57

标签: ruby-on-rails

这就是我在我的rails应用程序及其工作中正在做的事情,但我正在寻找一个更清洁的解决方案:

class Workorder < ActiveRecord::Base
  has_many :events, :through => :tasks
  def total_hours
    events.map{|e| e.hours}.reduce(:+)
  end

它给出了所有任务事件的总小时数:

workorder.total_hours

但是,我也有有孩子的工作人员:

  has_many :children, :class_name => "Workorder", :foreign_key => "parent_id"

我想知道所有孩子及其任务的总小时数。

这些不起作用:

  def total_children_hours
    self.children.events.map{|e| e.hours}.reduce(:+)
  end

  I get - undefined method `events'

  def total_children_hours
    self.children.map{|e| e.total_hours}.reduce(:+)
  end

  I get - nil can't be coerced into BigDecimal

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

我不知道你是否看过ActiveRecord Calculations.html但是你可以做到

def total_hours
  events.sum(:hours)
end

def total_children_hours
   events.children.sum(:hours)
end

我认为这是制作列总和的最简单方法

答案 1 :(得分:0)

那是因为你有很多孩子。每个人都有很多活动。

def total_children_hours
  hours = 0
  self.children(s).each do |children|
    hours += children.events.map{|e| e.hours}.to_i.reduce(:+)
  end
  hours
end

检查这个类似的主题:

Ruby on Rails nil can't be coerced into BigDecimal

的ActiveRecord ::计算

http://api.rubyonrails.org/classes/ActiveRecord/Calculations.html

答案 2 :(得分:0)

尝试解决方案:

class Workorder < ActiveRecord::Base
   has_many :events, :through => :tasks
   def total_hours
     events.map {|e| e.hours }.reduce(:+) || 0
   end
end

def total_children_hours
   children.map {|e| e.total_hours }.reduce(:+)
end
相关问题