如何在Rails之前修复价格字段?我收到了这个错误:
undefined method
before_filter'for Class:0x007fdddc1549d0>`
代码:
class Item < ActiveRecord::Base
before_filter :update_fields
private
def update_fields
self.price = self.price.to_s.gsub(',', '.').to_f
# getting this results if called in "before_save"
# 5.77 => 5.77
# 5,15 => 5.00
end
end
答案 0 :(得分:1)
所以,我已经将这个移动代码解决了控制器:
# encoding: utf-8
class ItemsController < ApplicationController
before_action :fix_fields
private
def fix_fields
if params[:item].present?
params[:item][:price] = params[:item][:price].to_s.gsub(',', '.').to_f
end
end
现在,如果用户输入:
5,75
保存5.75
答案 1 :(得分:0)
这就是我直接在模型中解决问题的方法,而不需要在控制器内部进行before_filter回调:
class Item < ActiveRecord::Base
before_validation :update_fields
private
def update_fields
[:field_1, :field_2, :field_3].each {|k|
self[k.to_sym] = self.attributes_before_type_cast[k.to_s].gsub(',', '.').to_f
}
end
end
希望它有所帮助!