开发者

Enter value A and B, then C = A+B, store A, B, C in database. Update value A or B will update sum C in database

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 v开发者_开发百科alues 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.


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


In your model

 before_save :calculate_c

 def calculate_c
    self.c = self.a + self.b
 end


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜