Ruby中sum数组项的问题

时间:2014-11-11 09:06:58

标签: ruby-on-rails ruby arrays

我在rails应用程序中计算数组项的总和时遇到了一些问题。 我有2个模特客户和队友。 目标是计算客户项目的利润。

型号:

class Client < ActiveRecord::Base
  belongs_to :user
  has_many :teammates
  .
  .
  .
  validates :project, presence: true
  validates :budget, presence: true
end

class Teammate < ActiveRecord::Base
  .
  .
  belongs_to :client
  .
  .
  validates :salary, presence: true
end

控制器:

class FrontPagesController < ApplicationController
  def front
    if signed_in?
      mess {current_user}
      @clients.each do |client|
        @client_teammates = current_user.teammates.where(client_project: client.project)
      end
    else
      redirect_to signin_path
    end
  end

  private

    def mess
      #multiple
        @teammates = yield.teammates.all
        @clients = yield.clients.all
      #single 
        @teammate = yield.teammates.build
        @client = yield.clients.build
    end
 end

公式为:Profit = @ client.budget - (@client_teammates工资总和) 那就是我被困住的地方。

我试图做以下

client.budget = 2000

客户有2个队友,薪水分别为1000和700

@clients.each do |client|
    @client_teammates.each do |c_t|
      %li
        a = %w(c_t.salary)
        sum = 0
        %span Profit: #{client.budget - (a.inject{|sum,x| sum + x }).to_i}

预计输出为:%span Profit: 300,但改为%span Profit: 1000; %span Profit:1300

1 个答案:

答案 0 :(得分:3)

@clients.each do |client|
    @client_teammates.each do |c_t|
      %li
        a = %w(c_t.salary) 
        sum = 0
        %span Profit: #{client.budget - (a.inject{|sum,x| sum + x }).to_i} 
end
  

预计输出为:%span Profit: 300,但得到%span Profit: 1000; %span Profit:1300

看看你是如何迭代队友并试图获得薪水的总和。

当你还有一个队友的集合时,应该执行步骤a = %w(c_t.salary)但是在你正在使用它的情况下,你只得到一个...你做了两次,每次只有一个队友

而不是@client_teammates.each,您可以pluck列出他们的工资,然后将它们减少到一个总和,或者更好的是,使用提供的sum方法-the-box由相同的API。

sum_of_teammate_salaries_for_client = @client_teammates.sum(:salary)

因此,您的代码可能如下所示:

@clients.each do |client|
    sum_of_teammate_salaries_for_client = @client_teammates.sum(:salary)
    %li
      %span Profit: #{client.budget - sum_of_teammate_salaries_for_client}
end