Ruby on rails 未保存类中的实例变量
我正在通过以下方式在验证前过滤PersonalInfo类的所有实例值:Ruby on rails 未保存类中的实例变量,ruby-on-rails,ruby,class,instance-variables,Ruby On Rails,Ruby,Class,Instance Variables,我正在通过以下方式在验证前过滤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_
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
此处讨论了此代码:
“条带”选项卡在转换时起作用:
“\t•\tzef”
为此:
“zef”
在我的测试用例中,我用错误的值(“\t•\tzef”)填写姓氏,当我在这里设置断点时:
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
结果如预期正确:
现在重要的部分不起作用了:
启动代码是因为我执行了以下操作:
info = PersonalInfo.new(params["personal_info"])
完成后,info.last_name仍然是错误的值:
问题:
为什么不保存实例变量
更多信息:
-‘rails’、‘3.2.17’
-ruby 1.9.3p484(2013-11-22修订版43786)[x86_64-darwin13.0.2]您必须调用
info.valid?
如果您没有直接保存
info
(这将隐式触发它),则触发验证挂钩。谢谢您的回答,先生。