1

我的视图模型上有 :meaning 和 :reading 属性。我想在将用户输入保存到数据库之前运行 sanitize before_validation 来清理用户输入。现在,不要输入这样的内容:

before_validation :sanitize_input

def sanitize_input
  self.meaning = ActionController::Base.helpers.sanitize(self.meaning)
  self.reading = ActionController::Base.helpers.sanitize(self.reading)
end

我想让它变得更好一点。所以我想出了一个 ActiveRecordExtension:

module ActiveRecordExtension
  extend ActiveSupport::Concern

  def sanitize_attribute(attribute)
    ActionController::Base.helpers.sanitize(attribute)
  end
end

ActiveRecord::Base.send(:include, ActiveRecordExtension)

现在我可以像这样调用清理输入:

def sanitize_input
  self.meaning = sanitize_attribute(self.meaning)
  self.reading = sanitize_attribute(self.reading)
end

我想通过在我的视图模型中做这样的事情(有点像属性本身的辅助方法)来缩短它:

def sanitize_input
  self.meaning.sanitize_attribute!
  self.reading.sanitize_attribute!
end

或者

def sanitize_input
  sanitize_attribute!(self.meaning)
  sanitize_attribute!(self.reading)
end

但是无论我尝试了什么,我都无法完成这项工作(在我的 sanitize_attribute 方法中使用 replace 和 bang (!) 的各种组合。

可以通过使用这样的东西进一步缩短它:

def sanitize_attributes!(*args)
  args.each do |arg|
    arg.replace ActionController::Base.helpers.sanitize(arg)
  end
end

并用类似的东西调用它:

sanitize_attributes!(self.meaning, self.reading)

当有多个属性需要清理时,最后一个会很方便。可以以某种方式以我希望它完成的方式之一完成吗?

4

1 回答 1

1

这些输入来自哪里,您必须手动清理它们?

试试这个:

def sanitize_attributes!(*attrs)
  attrs.each do |attr|
    dirty = self.send attr
    #this should mark the attribute as changed, so it's included with partial updates
    self.send "#{attr}=".to_sym, ActionController::Base.helpers.sanitize(dirty)
    #or
    #self.write_attribute(attr, ActionController::Base.helpers.sanitize(dirty))
  end
end

sanitize_attributes!(:meaning, :reading)
于 2013-09-07T15:48:11.537 回答