What is the best way to disinfect ruby ​​fields on rails

I currently have a controller capturing some html from TinyMCE on the front panel. If I messed around with firebug, you can send script tags and enter warning messages, etc. To the screen.

edit: I am currently fixing this in the model using the sanitize helper:

require 'action_view' class NotesController < AuthApplicationController include ActionView::Helpers::SanitizeHelper ... def update params[:note][:content] = sanitize(params[:note][:content], :tags => %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]) 

It seems useless in the controller. Is there a better way? That is, somehow integrate this ActiveRecord so that I can easily specify this for this and other fields before saving, similar to checking?

Thanks for any suggestions.

edit:

Take some steps here.

Under my / my faces

 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 

Then in my models the code collapses to

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

It seems like it's extra markup without too much fuss.

Pretty new to rails, so nervous that I can do something wrong. Can anyone see potential flaws here?

Thanks again

+7
source share
2 answers

I think the way you do this is fine, but if you use before_save , then you can potentially not check (since before_save is called after the check). In addition, you do not have to embed it in your own module, it may just be a private method for 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(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 
+11
source

This question seems to be answered, but for those who come to it, you might want to use custom mutators to make it 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(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 

This will ensure that the content is cleared at any time it is modified.

+1
source

All Articles