Activerecord 查找后,回调无法正常工作
我安装了Rails 4.1.6 型号Activerecord 查找后,回调无法正常工作,activerecord,ruby-on-rails-4,Activerecord,Ruby On Rails 4,我安装了Rails 4.1.6 型号报告: after_find :convert_decimal_to_float def convert_decimal_to_float self.mag = self.mag.to_f end 在rails控制台中: 2.1.2 :001 > r = Report.last ... 2.1.2 :002 > r.mag => #<BigDecimal:5032730,'0.31E1',18(36)> 问题是,为
报告
:
after_find :convert_decimal_to_float
def convert_decimal_to_float
self.mag = self.mag.to_f
end
在rails控制台中:
2.1.2 :001 > r = Report.last
...
2.1.2 :002 > r.mag
=> #<BigDecimal:5032730,'0.31E1',18(36)>
问题是,为什么我的after\u-find回调在这里不能正常工作?您的after\u-find回调实际上工作正常,但由于您的数据库列是DECIMAL类型,因此它将始终保存为BigDecimal。就像该列的类型是FLOAT一样,如果您尝试将BigDecimal数字保存到该列,它将转换并保存为浮点数 如果不知道在“找到”对象时需要转换的确切原因,就很难给出适当解决方法的建议,但这里有两个选项: 第一个选项:
attr_accessor :mag_floating_point # Virtual attribute
def convert_decimal_to_float
self.mag_floating_point = self.mag.to_f
end
您可以在数据库中创建两列。十进制列和浮点列
迁移
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
第二个选择,我认为会更好
报告模型
attr_accessor :mag_floating_point # Virtual attribute
def convert_decimal_to_float
self.mag_floating_point = self.mag.to_f
end
现在,您可以通过虚拟属性访问浮点,但请记住它不会持久存在。在我看来,这要干净得多