activerecord - after_find callback does not work properly -
activerecord - after_find callback does not work properly -
i have rails 4.1.6 installed.
model report
:
after_find :convert_decimal_to_float def convert_decimal_to_float self.mag = self.mag.to_f end
in rails console:
2.1.2 :001 > r = report.last ... 2.1.2 :002 > r.mag => #<bigdecimal:5032730,'0.31e1',18(36)>
but if utilize r.mag.to_f
, works fine:
2.1.2 :003 > r.mag.to_f => 3.1
the question is, why doesn't after_find callback work here?
your after_find callback working because database column of type decimal save bigdecimal. if column of type float if tried save bigdecimal number it, convert , save floating point number.
without knowing why require conversion upon "finding" object, hard give advice appropriate workaround here couple of options:
first option:
you can create 2 columns in database. decimal column , float column.
migration
add_column('report','mag', :decimal,:precision => 11, :scale => 9) # i've used random precision , scale, i'm not sure need add_column('report','mag_floating_point', :float)
report model
after_find :convert_decimal_to_float def convert_decimal_to_float self.mag_floating_point = self.mag # convert decimal number float , "assign" self.save # still need save object value has been assigned end
second option:
the sec alternative think alot better.
report model
attr_accessor :mag_floating_point # virtual attribute def convert_decimal_to_float self.mag_floating_point = self.mag.to_f end
you able access floating point through virtual attribute maintain in mind wont persist. in opinion, much cleaner.
activerecord ruby-on-rails-4
Comments
Post a Comment