0

目前我正在使用它来去除空格。

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 无法识别像这样直接使用的变量。

4

1 回答 1

1

好的,在
John TopleyJakob S的帮助下
(抱歉,新用户不能只有 1 个超链接,因此无法链接到他们的堆栈溢出配置文件)

并提出一个更简单的堆栈溢出问题

我已经能够提出以下有效的代码。
诀窍正在改变。

self.attributes[u] = Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s

to

self.send("#{u}=", Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s)

工作守则


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.send("#{u}=", Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s)
   end
 }
end
于 2009-06-16T13:54:00.070 回答