How to use calculated column with before_save in Rails

214 views Asked by At

Let assume I have an Order model with length:decimal, height:decimal and depth:decimal column. I have a model method that calculated the volume:

def volume
  length * height * depth
end

I have another method that calculated the special_volume:

def special_volume
  volume * 2.43
end

Let assume that I need now to save this calculated field in database, so I create volume:decimal and special_volume:decimal column.

I refactor my code to use before_save like this:

before_save do
  self.volume = set_volume
  self.special_volume = set_special_volume
end

private
  def set_volume
    length * height * depth
  end

  def set_special_volume
    volume * 2.43
  end

The issue is that in set_special_volume method, the volume or the self.volume is nil, because it's still not saved.

How do hundle that usecase in Rails? Do I need before_save?

0

There are 0 answers