11175
(-- --)
July 18, 2009, 4:50pm
1
Here's my current loop:
update_total = model.find(:all)
update_total.each do |row|
val = ((row.totoff + row.rushoff + row.passoff + row.scoroff +
row.rzonoff + row.fumlost + row.passhint + row.tolost + row.sacksall +
row.tackflossall + row.passeff + row.firdwns + row.thrdwncon +
row.fthdwncon)/14.0).round_to(4)
row.totals = val
row.save
puts "Team = #{row.team.name} and total val = #{val}."
end
This of course looks sloppy. I thought I could use something similar:
val = row.inject(0){|sum,item| sum + item}
.. but I can't figure out how to use this without it adding specific
columns, namely..
team_id, totals, compiled_on, created_at, updated_at
.. these 5 columns should be exempt from sums..
It's not overly important and I can work around it. I guess I just want
to keep my code as clean as possible and didn't know if there is a more
preferred way to sum up a row's totals in rails..
Thanks.
11175
(-- --)
July 18, 2009, 6:41pm
2
Älphä Blüë wrote:
[...]
.. but I can't figure out how to use this without it adding specific
columns, namely..
team_id, totals, compiled_on, created_at, updated_at
.. these 5 columns should be exempt from sums.
How about using [:column1, :column2, ...] - [:team_id, :totals, ...] ?
Remember, Array#- actually works in Ruby.
Best,
Instead of querying the model for all of this data, I recommend encapsulating this calculation in the model itself. Also, I’d give meaningful names to 14.0 and 4 to clearly communicate what purpose they serve in the calculation.
Then your loop could be:
Model.all.each do |model|
model.recalculate_total
model.save!
puts …
end
11175
(-- --)
July 19, 2009, 1:15pm
4
Hi Craig,
Did you mean something like this?
Both methods are in the model..
def recalculate_totals(row)
fields = 5.0
row.totals = ((row.kickret + row.puntret + row.netpunt +
row.kickretdef + row.puntretdef) / fields).round_to(4)
end
model.compiled_this_week.all.each do |row|
row.recalculate_totals(row)
row.save!
puts "Team = #{row.team.name} and total val = #{row.totals}."
end
Hi,
Yes, and Marnen’s observation in a later message about not needing to pass row is spot on.
Regards,
Craig
11175
(-- --)
July 19, 2009, 7:49pm
6
Thanks guys.
I changed it to:
def recalculate_totals
fields = 5.0
self.totals = ((self.kickret + self.puntret + self.netpunt +
self.kickretdef + self.puntretdef) / fields).round_to(4)
end
and..
model.compiled_this_week.all.each do |row|
row.recalculate_totals
row.save!
puts "Team = #{row.team.name} and total val = #{row.totals}."
end