目前我正在使用它来去除空格。
class Newsletter < ActiveRecord::Base
before_validation :clean_up_whitespace
end
def clean_up_whitespace
fields_to_strip = ['title','notes']
fields_to_strip.each { |f|
unless self.attributes[f].nil?
self.attributes[f].strip!
end
}
end
我想做一些类似的事情来摆脱 MS word 类型的 unicode。目前我使用:
require 'iconv'
class Newsletter < ActiveRecord::Base
before_validation :clean_up_unicode
end
def clean_up_unicode
unless title.blank?
self.title = Iconv.iconv('ascii//ignore//translit', 'utf-8', self.title).to_s
end
unless notes.blank?
self.notes = Iconv.iconv('ascii//ignore//translit', 'utf-8', self.notes).to_s
end
end
这种方法有效,但不是很干燥,因为我需要为 40 个表单字段执行此操作。
我原以为我可以使用类似的东西:
require 'iconv'
class Newsletter < ActiveRecord::Base
before_validation :clean_up_unicode
end
def clean_up_unicode
unicode_fields_to_clean = ['title','notes']
unicode_fields_to_clean.each { |u|
unless self.attributes[u].blank?
self.attributes[u] = Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s
end
}
end
我知道我不了解这种工作方式。
当我
用puts some_variable =替换
self.attributes[u] =时,
我得到了控制台的正确输出。我只是不知道如何将该变量恢复到表单中。
如果它有助于错误的代码是self.attributes[u] =我不知道用什么替换它。我原以为我可以使用self.VariableNameOfField =但 rails 无法识别像这样直接使用的变量。