2009-01-28 134 views
78

我正在寫一個模型來處理來自文本區域的用戶輸入。根據http://blog.caboo.se/articles/2008/8/25/sanitize-your-users-html-input的建議,我在使用before_validate回調保存到數據庫之前清理了模型中的輸入。在模型中使用助手:如何包含助手依賴項?

我的模型的相關部分是這樣的:

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 

不用說,這是行不通的。當我嘗試保存新帖子時,出現以下錯誤。

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

顯然,SanitizeHelper創建HTML :: WhiteListSanitizer的實例,但是當我把它組合成我的模型無法找到HTML :: WhiteListSanitizer。爲什麼?我能做些什麼來解決這個問題?

回答

109

只要改變第一行,如下所示:

include ActionView::Helpers 

,這將使它的工作。

UPDATE:對於Rails 3的使用:

ActionController::Base.helpers.sanitize(str) 

幸得lornc's answer

+0

不能說的更好自己 – Tilendor 2009-01-29 00:09:48

+1

謝謝。 我通過將include移到類定義的內部來實現它。 – 2009-01-29 01:00:13

+1

有了這個,我得到'堆棧層太深'。它在before_save方法中。 – Automatico 2013-08-01 00:35:31

121

這給你只是輔助方法不加載的副作用每::的ActionView方法助手到模型:

ActionController::Base.helpers.sanitize(str) 
22

要從您自己的控制器訪問助手,只需使用:

OrdersController.helpers.order_number(@order) 
9

我不會推薦任何這些方法。相反,把它放在它自己的命名空間中。

class Post < ActiveRecord::Base 
    def clean_input 
    self.input = Helpers.sanitize(self.input, :tags => %w(b i u)) 
    end 

    module Helpers 
    extend ActionView::Helpers::SanitizeHelper 
    end 
end 
2

如果你想使用一個模型裏面是helper_method my_helper_method,你可以寫:

ApplicationController.helpers.my_helper_method