Pregunta

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.

¿Fue útil?

Solución

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

Otros consejos

Actually it will be better to allow SQL to handle it.

<%= @obj_policy.amount_ensure + @obj_policy.vehicles.sum(:vehicle_value) %>

You can also wrap it into a instance method:

class Policy
   def total_value
     amount_ensure + vehicles.sum(:vehicle_value) # I don't remember if `to_i` is necessary here in case of empty collection, try it out
   end
end

It's also possible to write a custom SQL query that will do this summing in database. In case of original solution proposed it fetches ALL vehicles with ALL fields that might not be necessary at all. Try to use SQL as much as possible for aggregation jobs.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top