Reputation: 4202
I really couldn't find anything regarding this issue, and also I couldn't find a better way to describe this, so I am really sorry if the question it's bad.
I have a simple model:
field :weight, type: Integer
field :height, type: Integer
I would like to actually calculate and save the body mass index (which it's a simple mathematical formula), in a new field. In my research I have came with two options, but I am not sure if that's the correct way or I just getting lucky.
field :weight, type: Integer
field :height, type: Integer
field :bmi, type: Float, default: ->{ calc_bmi }
def calc_bmi
self.weight / ((self.height.to_f/100) ** 2)
end
Instantiating from the rails console works:
a = Tmodel.new(weight: 70, height: 170)
=> #<Tmodel _id: 535fe9506c75730fe8000000, created_at: nil, updated_at: nil, weight: 70.0, height: 170, bmi: 24.221453287197235>
before_save :calc_bmi
field :weight, type: Integer
field :height, type: Integer
field :bmi, type: Float
def calc_bmi
self.bmi = self.weight / ((self.height.to_f/100) ** 2)
end
From the console:
b = Tmodel.new(weight: 70, height: 170)
=> #<Tmodel _id: 535feab26c757315a4000000, created_at: nil, updated_at: nil, weight: 70.0, height: 170, bmi: nil>
b.save
b
=> #<Tmodel _id: 535feab26c757315a4000000, created_at: 2014-04-29 18:13:45 UTC, updated_at: 2014-04-29 18:13:45 UTC, weight: 70.0, height: 170, bmi: 24.221453287197235>
As I said both works, but I am not sure which one could be the right to use.
I'm using mongoid 4.0beta and rails 4.0.4.
Upvotes: 1
Views: 43
Reputation: 5213
You can use the second method as it will update the values before save every time there is change in height and weight. If you want to calculate the bmi only when you create the document the you can use the first method or you can use callback before_create.
Upvotes: 1