Sunday, March 27, 2011

Using helpers in model: how do I include helper dependencies?

I'm writing a model that handles user input from a text area. Following the advice from http://blog.caboo.se/articles/2008/8/25/sanitize-your-users-html-input, I'm cleaning up the input in the model before saving to database, using the before_validate callback.

The relevant parts of my model look like this:

include ActionView::Helpers::SanitizeHelper

class Post < ActiveRecord::Base {
  before_validation :clean_input

  ...

  protected

  def clean_input
    self.input = sanitize(self.input, :tags => %w(b i u))
  end
end

Needless to say, this doesn't work. I get the following error when I try and save a new Post.

undefined method `white_list_sanitizer' for #<Class:0xdeadbeef>

Apparently, SanitizeHelper creates an instance of HTML::WhiteListSanitizer, but when I mix it into my model it can't find HTML::WhiteListSanitizer. Why? What can I do about this to fix it?

From stackoverflow
  • Just change the first line as follows :

      include ActionView::Helpers
    

    that will make it works.

    Tilendor : couldn't have said it better myself
    O. Frabjous-Dey : Thanks. I got it to work by moving the include to inside of the class definition.
  • Alfreddd is right. This behavior seems to have changed with a recent version of actionpack.

    Also, the include must be moved within the class definition, or many, many things will break.

0 comments:

Post a Comment