[Newb] Adding database fields to get a total

Total newb here, as I’ve been working my way threw the tutorial, but
doing my own thing.
I’ve created a fairly simple app, that has a bunch of items. Each
item has 6-9 fields that have a cost associated with them (db field =
float). Think of each item as a car maintenance log, oil change =
$50.00, tires = 500, breaks = 230 etc… I want to be able to add up
all the fields associated with the item for a grand total.

I’ve read a lot and I"m not sure if I’m modifying the model, or coming
up with something fancy in the controller etc…

Any help with my baby steps is much appreciated.

THx

I’d suggest keeping that logic in the model…maybe create a method on
your model for getting “grand_total”.

This blog post should give you a better idea of why you’d want this
kind of logic in the model:

http://railstips.org/2008/12/30/move-it-to-the-model-and-use-tiny-methods

KR wrote:

Total newb here, as I’ve been working my way threw the tutorial, but
doing my own thing.
I’ve created a fairly simple app, that has a bunch of items. Each
item has 6-9 fields that have a cost associated with them (db field =
float). Think of each item as a car maintenance log, oil change =
$50.00, tires = 500, breaks = 230 etc… I want to be able to add up
all the fields associated with the item for a grand total.

I’ve read a lot and I"m not sure if I’m modifying the model, or coming
up with something fancy in the controller etc…

Any help with my baby steps is much appreciated.

THx

You -could- do it this way:

Table item
… list of items

Table work_done
… list of things done

Table work_done_on_items
… item_id and work_done_id

And you could then just run a simple query for the sum of all the things
associated with that item… Or if you really wanted to, put the ‘total’
in the ‘item’ table and then you’d have to do “on_change” on the other
table so it updates the total every time an item is added, removed, or
changed…

hope this helps.

Create a virtual attribute in the model that returns the grand total.

def grand_total
field_1 + field_2 …
end

You can then reference grand_total from your views like any other
attribute.

E. Litwin wrote:

Create a virtual attribute in the model that returns the grand total.

def grand_total
field_1 + field_2 …
end

You can then reference grand_total from your views like any other
attribute.

I probably like that answer the best so far :slight_smile:

Sweet thanks it worked. Not so bad after all!

On Aug 24, 12:43 pm, Aldric G. <rails-mailing-l…@andreas-

Some good replies already, but I’d add that you almost certainly want
to avoid float fields for money. They are OK for some things, but
people get twitchy when money doesn’t add up exactly. You’re probably
better off either using decimal fields or just storing values in
integer cents.

–Matt J.