0

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.

Community
  • 1
  • 1
Victor
  • 13,010
  • 18
  • 83
  • 146

4 Answers4

1

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
  • 10,910
  • 6
  • 43
  • 40
  • But if the entry is new? Then the first save will give problem, won't it? – Victor Oct 27 '10 at 14:53
  • 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 Oct 27 '10 at 14:58
  • Should I enter this in model or controller? – Victor Oct 27 '10 at 15:02
  • You probably should pick up a Rails book :) Agile Web Development With Rails explains it all to you. – Ariejan Oct 27 '10 at 20:02
  • Half way then I stopped, but will do it again when I have time. Appreciate your advice and help all over SO! – Victor Nov 01 '10 at 17:57
1

In your model

 before_save :calculate_c

 def calculate_c
    self.c = self.a + self.b
 end
Anna
  • 1,479
  • 12
  • 14
0

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

wolfcry911
  • 46
  • 1
  • 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 Oct 28 '10 at 12:25
  • I still don't follow. Whatever method used to extract a and b can then calculate c dynamically. – wolfcry911 Nov 06 '10 at 13:21
0

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
  • 4,302
  • 22
  • 22