How to store / use a calculated field? - Intermediate Noob -

Hey Everyone

I’m not sure how to ask this properly - that’s probably the reason I’m
not sure how to implement it. I’m an intermediate noob and I’m not
sure how to bring this together…

Here’s my scenerio…

people using my system record “readings” every month to determine
month to month usage. Here’s the calculation…

{ This months reading} - {last months reading} = the usage for this

When adding a new reading record I want the system to look at the two
readings, calculate the usage, and then insert it possibly using an
“after_save” function to store the usage. Here’s the basic idea, but
I’m not sure how to implement it - any ideas or suggestions would be
helpful. This seems to be something I would want to handle in my
model, but then I’m not sure how I call it when I save the record.

def get_usage(id,lastmonth,reading)

@last_month=Readings.find(:all, :conditions=[:month =>
lastmonth, :id=>id])
current_usage =reading-@last_month.reading
return current_usage

Any help is appreciated.



2009/9/19 internetchris [email protected]:

month to month usage. Here’s the calculation…

def get_usage(id,lastmonth,reading)

 @last_month=Readings.find(:all, :conditions=[:month =>
lastmonth, :id=>id])
 current_usage =reading-@last_month.reading
return current_usage

A question, is it necessary to store this in the db at all? I am not
sure from your post but it seems that this could be calculated any
time it is needed. If that is so then I would suggest, initially at
least, not storing it at all. Provide a model method, usage or
whatever is appropriate, that looks up the relevant records and
returns the value. Then if in the future you decide for efficiency
reasons that you must save this in the db it is only a matter of
storing it as appropriate and changing your usage method to return the
saved value direct from the db. One of the issues with saving it is
that if you later edit one of the records that it is calculated from
you must remember to update the saved value.


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs