legendary_rob
legendary_rob

Reputation: 13002

Rails/Sql summing attributes of child element

This seems like a simple thing to do but i cant figure it out.

a scorecard has a skills_development, which has many training_programs, which has many participants. each participant has an attribute called training_facility_cost i need to take it up an level and find out what the facility cost is for an entire training_program.

so summing all the facility_cost attributes for each child partipant. what is the best way around such a problem. should i do this in a sql query or would using a nested block be more efficient.

something like

s.skills_development.training_programs.each do |tp|
  costs = []
  tp.participants.each {|p| costs << p.training_facility_cost}
  costs.inject(:+)
end

that doest work though i get

NoMethodError: undefined method `+' for nil:NilClass

, i think its because all of them have null for the attribute. so its not counting it as zero??

anyone know how to do this fast and simple??

Upvotes: 0

Views: 89

Answers (1)

TM.
TM.

Reputation: 3741

Try out something like this

skills_development.participants.to_a.sum { |p| p.training_facility_cost }

Upvotes: 1

Related Questions