Best Practices? - probably a newbie question


#1

Hi:

Can anyone point me to a document of best practices? Here is my
situation. I can think of 3 solutions, but which is best? There may
be more solutions I have not considered, so feel free to let me know
those also.

I have a line like this

@x = model.find(:all, :conditions=>blah, blah, blah) (which will
lead to a small number of records, typically less than 100)

I wish to calculate the total of @x.time.

A. I could do that by making another call to the db and asking it to
give me the total and place that value in a new variable then use
that variable in my rhtml file. That would keep calculations where
they belong - off the presentation layer. But it makes another call
to the db.

B. I could use a for loop and run through the values in @x.time
totalling them as I go. That would avoid a hit to the db but it
would involve running through the same array twice, once on the
controller and once in the rhtml page where I am displaying a table
row for each element of the array. So this has duplicated effort.

C. I could just do the totalling while using the “for” loop on the
rhtml page (the one that makes one row of a table for each row from
the db. This saves a double hit to the db or a double looping
through the array but seems to clutter up the rhtml file with things
(calculations) that should not be there.

What “best practice” would experienced rails programmers suggest?

bruce


#2

in controller:

@x = X.find(:all, …)
@x_time_total = @x.inject(0) { |total, x| sum + x.time }

this is the cleanest approach in my opinion.


#3

Chris:

Thank you.

bruce