如何最好地清理轨道上的ruby中的字段

我目前有一个控制器从前端的TinyMCE捕获一些html。 如果我修改了firebug,则可以向屏幕提交脚本标记并注入警报消息等。

编辑:目前我正在使用sanitize帮助器在模型中修复它:

require 'action_view' class NotesController  %w(a object p param h1 h2 h3 h4 h5 h6 br hr ul li img), :attributes => %w(href name src type value width height data) ); @note.update_attributes(params[:note]) 

这在控制器中感觉很乱。 有没有更好的办法? 即以某种方式集成这个ActiveRecord所以我可以很容易地指定这个和其他字段这样做,然后以类似的方式保存validation?

谢谢你的任何建议。

编辑:

在这里取得一些进展。

在我的/ Libs下我有

 module SanitizeUtilities def sanitize_tiny_mce(field) ActionController::Base.helpers.sanitize(field, :tags => %w(abi 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 

然后在我的模型中代码折叠到

 class MyModel < ActiveRecord::Base include ::SanitizeUtilities ... before_save :sanitize_content ... def sanitize_content self.content = sanitize_tiny_mce(self.content) end end 

这似乎消除了不必要的标记而没有太多的麻烦。

铁轨这么紧张我可能会做错事。 任何人都可以看到潜在的缺点吗?

再次感谢

我认为你这样做的方式很好,但如果你使用的是before_save那么你可能仍然无法通过validation(因为在validation之后调用了before_save )。 此外,您不一定要将它放入自己的模块中,它可能只是您class级的私有方法。

就像是:

 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(abi 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 

这个问题似乎得到了回答,但是对于任何人来说,你可能会考虑使用自定义mutators来使这个更加透明。 就像是:

 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(abi 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 

这将确保内容在更改时进行清理。