How best to sanitize fields in ruby on rails

心不动则不痛 提交于 2019-11-30 13:48:22

I think the way you are doing it is fine, but if you are using before_save then you could potentially still fail validations (since before_save is called after validations). Also, you don't necessarily have to put it into it's own module, it could just be a private method on your class.

Something like:

class MyModel < ActiveRecord::Base

  before_validation :sanitize_content, :on => :create

  private
    def sanitize_content
      self.content = sanitize_tiny_mce(self.content)
    end
    def sanitize_tiny_mce(field)
      ActionController::Base.helpers.sanitize(field,
        :tags => %w(a b i strong em p param h1 h2 h3 h4 h5 h6 br hr ul li img),
        :attributes => %w(href name src type value width height data) );
    end

end

This question seems to be answered but for anyone coming to this you might want to consider using custom mutators to make this more transparent. Something like:

class MyModel < ActiveRecord::Base
  def content= content
    write_attribute(:content, sanitize_tiny_mce(content)
  end

  private

  def sanitize_tiny_mce content
    ActionController::Base.helpers.sanitize(field,
        :tags => %w(a b i strong em p param h1 h2 h3 h4 h5 h6 br hr ul li img),
        :attributes => %w(href name src type value width height data)
    );
  end
end

This will ensure the content is sanitized any time it's changed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!