类中的实例变量未保存

时间:2014-05-23 09:58:59

标签: ruby-on-rails ruby class instance-variables

我正在通过before_validation过滤我的PersonalInfo类的所有实例值,如下所示:

  before_validation :strip_tabs

  def strip_tabs
    self.instance_variables.map do |attr|
      value = self.instance_variable_get(attr)
      if value.present? && value.kind_of?(String)
        encoding_options = {
          :invalid           => :replace,  # Replace invalid byte sequences
          :undef             => :replace,  # Replace anything not defined in ASCII
          :replace           => '',        # Use a blank for those replacements
          :universal_newline => true       # Always break lines with \n
        }
        value = value.encode(Encoding.find('ASCII'), encoding_options)
        value = value.squish 
        value = value.gsub("/t","") 
        self.instance_variable_set(attr, value)
      end
    end  
  end

此处讨论了此代码:

Before Validation loop through self attributes for modification

strip_tabs可以解决这个问题: “\ t•\ tzef” 进入: “ZEF”

在我的测试用例中,我使用错误值(“\ t•\ tzef”)填写last_name,并在此处设置断点:

  def strip_tabs
    self.instance_variables.map do |attr|
      value = self.instance_variable_get(attr)
      if value.present? && value.kind_of?(String)
        encoding_options = {
          :invalid           => :replace,  # Replace invalid byte sequences
          :undef             => :replace,  # Replace anything not defined in ASCII
          :replace           => '',        # Use a blank for those replacements
          :universal_newline => true       # Always break lines with \n
        }
        value = value.encode(Encoding.find('ASCII'), encoding_options)
        value = value.squish 
        value = value.gsub("/t","") 
        self.instance_variable_set(attr, value)
      end
    end  
binding.remote_pry
  end

结果符合预期:

enter image description here

现在不起作用的重要部分:

代码启动是因为我这样做:

info = PersonalInfo.new(params["personal_info"])

当它完成时,info.last_name仍然是坏值: enter image description here

问题: 为什么不保存instance_variables?

更多信息: - 'rails','3.2.17' - ruby​​ 1.9.3p484(2013-11-22修订版43786)[x86_64-darwin13.0.2]

1 个答案:

答案 0 :(得分:3)

您必须致电

info.valid?

如果你没有直接保存info(这会隐式触发它),就会触发验证钩子。