after_find回调无法正常工作

问题描述:

我安装了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回调在这里正常工作?

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

现在您就可以通过你的虚拟属性来访问浮点但请记住,它不会持续。在我看来,这更清洁。