How to run a method from a mongoid class, using existing values from a document in Rails?

StackOverflow https://stackoverflow.com/questions/23372363

  •  12-07-2023
  •  | 
  •  

Pergunta

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.

First method: using default value

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>

Second method: using callbacks

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.

Foi útil?

Solução

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.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top