title: How best to sanitize fields in ruby on rails
body: <p>I currently have a controller capturing some html from TinyMCE on the front end. If I tinker with firebug it is possible to submit script tags and inject alert messages etc on to the screen.</p>
  
  <p>edit: Currently I am fixing this in the model by using the sanitize helper:</p>
  
  <pre><code>require 'action_view'
  
  class NotesController &lt; AuthApplicationController
  
    include ActionView::Helpers::SanitizeHelper
  ...
    def update
      params[:note][:content] = sanitize(params[:note][:content],
          :tags =&gt; %w(a object p param h1 h2 h3 h4 h5 h6 br hr ul li img),
          :attributes =&gt; %w(href name src type value width height data) );
  
      @note.update_attributes(params[:note])
  </code></pre>
  
  <p>This feels messy in the controller. Is there a better way? I.e. somehow integrate this ActiveRecord so I can easily specify to do this to this and other fields before saving in a similar way to validation?</p>
  
  <p>Thanks for any suggestions.</p>
  
  <p>edit:</p>
  
  <p>Making some progress here.</p>
  
  <p>Under my /Libs I have</p>
  
  <pre><code>module SanitizeUtilities
    def sanitize_tiny_mce(field)
      ActionController::Base.helpers.sanitize(field,
        :tags =&gt; %w(a b i strong em p param h1 h2 h3 h4 h5 h6 br hr ul li img),
        :attributes =&gt; %w(href name src type value width height data) );
    end
  end
  </code></pre>
  
  <p>Then in my Models the code collapses to</p>
  
  <pre><code>class MyModel &lt; ActiveRecord::Base
    include ::SanitizeUtilities
  ...
    before_save :sanitize_content
  ...
    def sanitize_content
      self.content = sanitize_tiny_mce(self.content)
    end
  
  end
  </code></pre>
  
  <p>This seems to strip out unwanted markup without too much fuss.</p>
  
  <p>Pretty new to rails so nervous I might be doing something wrong. Can anybody see potential drawbacks here?</p>
  
  <p>Thanks again</p>