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

时间:2011-07-05 14:57:20

标签: ruby-on-rails ruby-on-rails-3

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

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

sub(/,/,".")

我如何在Rails3中执行此操作?

2 个答案:

答案 0 :(得分: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

数字是您要转换的属性。

我假设您不需要将其转换回逗号表示以显示给用户?如果这样做,您可能需要查看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

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

答案 1 :(得分:0)

我玩了它并发现了这个:

假设在表单字段数字中,用户输入值'12,13'。

从表单转到PostController到'create'方法

 class PostController < ApplicationController
 def create
   @post = Post.new(params[:post]) 
   #on this step instance of Post model created, validated and filled with relevant values
   #so @post.number == '12' #(decimal), it cuts ',13'
   #we need to redefine @post.number
   @post.number = params[:post][:number].gsub(/,/,'.').to_f # => 12.13
   #and after that save the post
   @post.save
 end
相关问题