保存到数据库之前处理数据

Vla*_*nov 3 ruby-on-rails ruby-on-rails-3

我的数据库中有十进制字段.用户可以输入两种格式的值:逗号或点(11,11或11.11).

但MySQL允许仅以"点"格式保存数据,所以我想在使用正则表达式保存之前处理数据,如下所示:

sub(/,/,".")
Run Code Online (Sandbox Code Playgroud)

我怎么能在Rails3中做到这一点?

Jam*_*sDS 15

如果我理解正确,可以在控制器或模型中完成.我可能会使用模型中的before_save回调来实现以下方式:

class Item < ActiveRecord::Base
  before_save :standardise_numbers
  ...

  protected

  # Called before this object is saved to the DB
  def standardise_numbers
    self.number.sub!(",", ".")
  end
end
Run Code Online (Sandbox Code Playgroud)

其中是你想要转换的属性.

我假设您不需要将其转换回逗号表示以显示给用户?如果这样做,您可能需要查看Rails的国际化API,Il8n.它处理这种东西和更多,所以绝对值得研究.

替代解决方案(编辑)

根据您的反馈,我的上述解决方案不起作用,因为数字已经转换,小数部分在传递到模型时丢失.可以在控制器中使用类似的代码来拦截和转换params散列本身中的数字:

class PostController < ActionController
  before_filter :standardise_numbers, :only => [ :create, :update ]

  def create
    @post = Post.create(params[:post])
  end

  protected

  # Intercepts the params hash
  def standardise_numbers
    params[:post][:number].sub!(",", ".")
  end
end
Run Code Online (Sandbox Code Playgroud)

这简化了创建和更新方法,允许您以通常的方式处理哈希.