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?
A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words . This method is helpful whenever you want to display time in this specific format.
In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.
Just change the first line as follows :
include ActionView::Helpers
that will make it works.
UPDATE: For Rails 3 use:
ActionController::Base.helpers.sanitize(str)
Credit goes to lornc's answer
This gives you just the helper method without the side effects of loading every ActionView::Helpers method into your model:
ActionController::Base.helpers.sanitize(str)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With