views:

48

answers:

4

Just to simplify my question here: Update Geocode latitude and logitude everytime address is updated

I wanna do this:

Two input field for user to enter values for A, B. When it is saved, value A and B are saved to the database. In the database column, there is a column C, which dynamically C = A + B.

First save:

A = 1 B = 2 C = A + B = 3

Then when user updates value for A and B, C is also changed dynamically and replace the new sum value in the database.

A = 2 B = 2 Now C will calculate: C = A + B = 4

Now value C is 4 instead of 3.

Can anyone write this thing in Rails? Thanks.

+1  A: 

I can!

The key are callbacks. This will update C before you save the object.

before_save :update_c

def update_c
  self.c = a + b
end
Ariejan
But if the entry is new? Then the first save will give problem, won't it?
Victor
Dude, I think you roughly saved my life by half at the moment. I am checking out callbacks and they look promising to what I have been looking for hours! Thanks! I'm a noob in Ruby on Rails, and am learning it by "reverse engineering" method which I have no choice!
Victor
Should I enter this in model or controller?
Victor
You probably should pick up a Rails book :) Agile Web Development With Rails explains it all to you.
Ariejan
+1  A: 

In your model

 before_save :calculate_c

 def calculate_c
    self.c = self.a + self.b
 end
Anna
A: 

forgive me for asking, but why store C in the first place? Won't having a and b on hand always satisfy c?

wolfcry911
Yes, but in this case the poster wants to geo-encode an address to lat,lng - the a-b-c is just an abstraction of that problem. Having lat,lng in you db for queries is much easier.
Ariejan
A: 

I'd say that this is a design smell. If the value of C is always A + B, then there is no need to store it in the database at all. Either the code that retrieves A & B can do the calculation, or a suitable database query can fetch A & B and calculate the value of C, before returning all three to the calling code.

But, given that A & B are latitude & longitude and C is and address, I may be wrong.

belugabob