2014-11-05 82 views
1

我安裝了Rails 4.1.6。after_find回調無法正常工作

型號Report

after_find :convert_decimal_to_float 

def convert_decimal_to_float 
    self.mag = self.mag.to_f 
end 

在軌控制檯:

2.1.2 :001 > r = Report.last 
... 
2.1.2 :002 > r.mag 
=> #<BigDecimal:5032730,'0.31E1',18(36)> 

但是,如果使用r.mag.to_f,它工作正常:

2.1.2 :003 > r.mag.to_f 
=> 3.1 

的問題是,爲什麼不我的after_find回調在這裏正常工作?

回答

1

您的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 

現在您就可以通過你的虛擬屬性來訪問浮點但請記住,它不會持續。在我看來,這更清潔。