【问题标题】:Processing data before saving to database在保存到数据库之前处理数据
【发布时间】:2011-07-05 14:57:19
【问题描述】:

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

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

sub(/,/,".")

如何在 Rails3 中做到这一点?

【问题讨论】:

  • 您想验证模型或视图中的数据?
  • 不,通过验证器验证数据,然后以两种格式(使用“,”或“。”)进入控制器的保存方法。此时我想将','转换为'。'

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


【解决方案1】:

如果我理解正确,这可以在控制器或模型中完成。我可能会使用模型中的 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

其中 number 是您要转换的属性。

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

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

【讨论】:

  • 模型将原始值转换为十进制并剪切 ',11' 部分,所以self.number =&gt; 11(十进制)我无法应用sub
  • 这是有道理的,因为 ActiveRecord 知道数据库期望什么数据类型,它必须相应地转换所有内容。您可以在控制器中使用before_filter 直接对params[:item][:number] 进行操作,从而避免在创建和更新方法中重复该代码(如果您使用params[:item] 哈希直接调用创建/更新)通缉)。
  • 创建一个内部属性来存储 params[:post][:number] 的原始形式(你可以在构建 Item 时这样做)。然后你可以在 before_save 回调中使用它来获取你需要的值。
  • @JamesDS 感谢您的帮助,替代方法完美!
  • 不客气,我很高兴能帮上忙! Dave Issacs 的想法也是一个不错的想法 - 看到一个演示如何使用内部属性完成它的答案会很酷。
【解决方案2】:

我玩了一下,发现了这个:

假设在表单字段 number 中,用户输入值 '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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-11
    • 1970-01-01
    • 2016-04-23
    相关资源
    最近更新 更多