I did an app to sum the last values of each column but i'm getting the total sum
Here my tables
|policies|
|id| |num_policy|
1 1234
2 4567
|insurances|
|id| |id_policy| |net_insurance|
1 1 4000
2 1 6000
3 2 3000
4 2 7000
I'm trying to do in excel
|id| |num_policy| |net_insurance|
1 1234 4000
2 4567 7000
sum = 11000
This is my controller
class PolicyController < ApplicationController
def generate_print
@policies= Policy.find(:all)
@dolar = Insurance.sum(:net_insurance)
respond_to do |format|
format.html
format.xls { send_data render_to_string(:partial=>"report_by_sum"), :filename => "Report_#{Date.today}.xls" }
end
end
end
This is my model
class Policy < ActiveRecord::Base
has_many :insurances
end
class Insurance < ActiveRecord::Base
belongs_to :policy
has_many :insurance_financing_details
end
This is my view showing the last insurance of each policy
<% @policies.each do |policy| %>
<%= policy.num_policy %>
<% policy.insurances.last(1).each do |insurance| %>
<%= insurance.net_insurance %>
<% end %>
<% end %>
<%= link_to "Export Excel",{:controller=>"policy",:action=>"generate_print" ,:format=>"xls"} %>
This is my partial view that i'm trying to sum it should show "11000" but i got "20000"
# _report_by_sum.erb
<%= @dolar %>
Someone can help me with this issue please?
I will really appreciate help
This line
@dolar = Insurance.sum(:net_insurance)
Calculates the sum of all insurance entries, i.e. 4000 + 6000 + 3000 + 7000.
You have to fetch the last insurance for each policy instead:
@dolar = @policies.to_a.sum { |policy| policy.insurances.last.net_insurance }