Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
O. Frabjous-Dey Avatar asked Jan 28 '09 22:01

O. Frabjous-Dey


People also ask

How do helpers work in Rails?

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.

Can we use helper method in controller rails?

In Rails 5, by using the new instance level helpers method in the controller, we can access helper methods in controllers.


2 Answers

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

like image 165
Alfreddd Avatar answered Oct 11 '22 15:10

Alfreddd


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) 
like image 31
lornc Avatar answered Oct 11 '22 17:10

lornc