Reputation: 91
I'm new to Rails and coding in general, and I'm trying to teach myself by working on an app for a delivery driver. I have a table called loads, and included are the columns for Gross Weight, tare weight and net weight. The way it is currently, the driver would have to type in all 3 weights manually. I'm trying to figure out the best way to have the app calculate the net weight (by subtracting the tare weight from the gross weight)and add it to the net column. This would cut down on the driver making a simple math mistake. I'm using MySQL, can someone point me in the right direction?
Upvotes: 0
Views: 182
Reputation: 106882
I would add a before_validation
callback to the model and let is calculate the missing value. Something like this:
# in your model
before_validation :calculate_net_weight
private
def calculate_net_weight
self.net_weight = gross_weight - tare_weight
end
Btw. I would argue that is makes sense to store all three values in the database even if you could calculate one from the other two. But having all three values in the databse might help to fix problems or might make calculation or statistics easier.
Upvotes: 3
Reputation: 1364
I would also ask why you have to store it in the database. If you do want to store it none the less:
You can create the before_create lifecyle hook of a model to calculate and set values before saving it to the database.
Upvotes: 1
Reputation: 819
why keep that logic in the database? You could simply have it in the model.
Let's say you have a Load model
simply add the following method
def net_weight
gross_weight - tare_weight
end
Upvotes: 2