在模型中使用助手:如何包含助手依赖项? [英] Using helpers in model: how do I include helper dependencies?

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

问题描述

我正在编写一个模型来处理来自文本区域的用户输入.遵循 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天全站免登陆