I faced some issue with calculating sum for array items in my rails app. I have 2 models Clients and Teammates. The goal is to calculate profit from Client project.
Models:
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
Controller:
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
The formula is: Profit = @client.budget - (sum of @client_teammates salaries) That's where I'm stuck.
I'v tried to do the following
client.budget = 2000
client has 2 teammates with salary of 1000 and 700 accordingly
@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}
Expect output to be: %span Profit: 300 , but got %span Profit: 1000; %span Profit:1300 instead.