Ruby on rails Rails在模型中求和相关记录

Ruby on rails Rails在模型中求和相关记录,ruby-on-rails,Ruby On Rails,这就是我在我的rails应用程序上所做的事情,它正在工作,但我正在寻找一个更干净的解决方案: class Workorder < ActiveRecord::Base has_many :events, :through => :tasks def total_hours events.map{|e| e.hours}.reduce(:+) end 但是,我也有带孩子的训练计划: has_many :children, :class_name => "

这就是我在我的rails应用程序上所做的事情,它正在工作,但我正在寻找一个更干净的解决方案:

class Workorder < ActiveRecord::Base
  has_many :events, :through => :tasks
  def total_hours
    events.map{|e| e.hours}.reduce(:+)
  end
但是,我也有带孩子的训练计划:

  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

谢谢你的帮助

那是因为你有很多孩子。每一个都有许多事件

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
检查类似的螺纹:

ActiveRecord::计算


我不知道你是否看过,但你可以

def total_hours
  events.sum(:hours)
end

def total_children_hours
   events.children.sum(:hours)
end
我认为这是对一列求和的最简单方法,请尝试以下解决方案:

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
class Workorder:任务
def总小时数
events.map{e|e.hours}.reduce(:+)| 0
结束
结束
def总儿童小时数
children.map{| e | e.total_hours}.reduce(:+)
结束

谢谢您的帮助。使用您的解决方案,我得到了“nil不能强制转换为BigDecimal”我将self.children.each更改为self.children.eachy您得到的是一个尝试添加的nil结果。使用:to|i.将其转换为整数。我稍微修改了一下,它的工作时间为'hours+=child.events.map{| e | e.hours}。如果child.events.count>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