Search code examples
ruby-on-railsrubyruby-on-rails-2

Sum 2 columns a value with array


Hello everybody.

I'm trying to sum 2 columns(amount_ensure and vehicle_Value) from different tables in my view

TABLES
|POLICIES|
 |id|   |amount_ensure|

|POLICY_VEHICLES| 
 |id|   |policy_id|

|VEHICLES|
 |Id|   |vehicle_value|

Here is my controller

def view_policy    
   @obj_policy = Policy.find(params[:id])
end

Here is my model

class Policy < ActiveRecord::Base
  has_many :policy_vehicles
  has_many :vehicles, :through => :policy_vehicles
end

class PolicyVehicle < ActiveRecord::Base
  belongs_to :vehicle
  belongs_to :policy
end

class Vehicle < ActiveRecord::Base
  belongs_to :policy
  has_many :policy_vehicles
  has_many :policies, :through => :policy_vehicles
end

Here is my view when in my partial view @obj_policy.vehicle is empty show only amount_ensure but when has value do SUM (but is an array from my partial view)

<% if @obj_policy.vehicles.empty? %> 
  Sum:
  <%= @obj_policy.amount_ensure %>           
<% else %>
  Sum:
  <%= @obj_policy.amount_ensure + @obj_policy.vehicles.vehicle_value.to_i %>           
<% end %>

<%= render :partial=>"vehicles" %>

My partial view

<% @obj_policy.vehicles.each do |vehicle| %>
   <%=  vehicle.vehicle_value %>
<% end %>

How can i fix this problem?

I will appreciate help.


Solution

  • This should work

    <% else %>
      Sum:
      <%= @obj_policy.amount_ensure + @obj_policy.vehicles.collect(&:vehicle_value).sum %>           
    <% end %>
    

    @obj_policy.vehicles.collect(&:vehicle_value).sum will be 0 when vehicles array is empty