使用模型助手:我怎么有帮助的依赖? [英] Using helpers in model: how do I include helper dependencies?

查看:195
本文介绍了使用模型助手:我怎么有帮助的依赖?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在写一个处理从一个文本区域用户输入一个模型。继意见<一个href="http://web.archive.org/web/20090416200046/http://blog.caboo.se/articles/2008/8/25/sanitize-your-users-html-input">http://blog.caboo.se/articles/2008/8/25/sanitize-your-users-html-input,我清理输入模型保存到数据库中,使用before_validate回调之前。

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>

显然,SanitizeHelper创建HTML :: WhiteListSanitizer的实例,但是当我混合成我的模型无法找到HTML :: WhiteListSanitizer。为什么?我能做些什么这个解决?

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?

推荐答案

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

Just change the first line as follows :

include ActionView::Helpers

这会使它的工作原理。

更新:对于Rails 3中使用:

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

幸得 lornc的回答

这篇关于使用模型助手:我怎么有帮助的依赖?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆