您的after_find回調實際上正常工作,但由於您的數據庫列的類型是DECIMAL,它將始終保存爲BigDecimal。就像列的類型是FLOAT一樣,那麼如果您嘗試將一個BigDecimal數字保存到它,它將轉換並保存爲浮點數。
沒有確切知道爲什麼你需要轉換在「發現」你的對象,它很難給出任何意見,以一個合適的解決辦法,但這裏有幾個選項:
第一個選項:
您可以在數據庫中創建兩列。 DECIMAL列和FLOAT列。
遷移
add_column('report','mag', :decimal,:precision => 11, :scale => 9) # I've just used random precision and scale, I'm not sure what you would need
add_column('report','mag_floating_point', :float)
報表模型
after_find :convert_decimal_to_float
def convert_decimal_to_float
self.mag_floating_point = self.mag # this will convert decimal number to float and "Assign"
self.save # you will still need to save the object as the value has only been assigned
end
第二個選項:
,我覺得這是好多了第二個選項。
報表模型
attr_accessor :mag_floating_point # Virtual attribute
def convert_decimal_to_float
self.mag_floating_point = self.mag.to_f
end
現在您就可以通過你的虛擬屬性來訪問浮點但請記住,它不會持續。在我看來,這更清潔。