Forum: Ruby on Rails Best Practices? - probably a newbie question

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
brucebalmer (Guest)
on 2005-11-26 14:37
(Received via mailing list)
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
christopher.k.hall (Guest)
on 2005-11-26 15:25
(Received via mailing list)
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.
brucebalmer (Guest)
on 2005-11-27 05:35
(Received via mailing list)
Chris:

Thank you.

bruce
This topic is locked and can not be replied to.