Using helpers in model: how do I include helper dependencies?

我正在编写一个模型来处理来自文本区域的用户输入。遵循来自 http://blog.caboo.se/articles/2008/8/25/sanitize-your-users-html-input的建议,在保存到数据库之前,我将使用 before _ validalback 清理模型中的输入。

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>

显然,SanitieHelper 创建了一个 HTML: : WhiteListSanitizer 的实例,但是当我将它混合到我的模型中时,它找不到 HTML: : WhiteListSanitizer。为什么?我该怎么做才能修好它?

111307 次浏览

只需将第一行修改如下:

include ActionView::Helpers

这样才能成功。

更新: 用于 Rails 3:

ActionController::Base.helpers.sanitize(str)

这要归功于 Lornc 的回答

这样就只有 helper 方法,而没有将每个 ActionView: : Helpers 方法加载到模型中的副作用:

ActionController::Base.helpers.sanitize(str)

要从您自己的控制器访问助手,只需使用:

OrdersController.helpers.order_number(@order)

我不建议使用这些方法中的任何一种,而是将其放在自己的名称空间中。

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

这对我来说更有效:

简单:

ApplicationController.helpers.my_helper_method

预告:

class HelperProxy < ActionView::Base
include ApplicationController.master_helper_module


def current_user
#let helpers act like we're a guest
nil
end


def self.instance
@instance ||= new
end
end

资料来源: http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model

如果你想在模型中使用 my_helper_method,你可以写:

ApplicationController.helpers.my_helper_method

In Rails 7:

full_sanitizer = Rails::Html::FullSanitizer.new
full_sanitizer.sanitize("<a href="javascript:alert('hacked!')">Some dangerous input</a>")

可用消毒剂清单: https://github.com/rails/rails-html-sanitizer#sanitizers

那么,你的模型将是:

class Post < ActiveRecord::Base {
before_validation :clean_input


...


protected


def clean_input
full_sanitizer = Rails::Html::FullSanitizer.new
self.input = full_sanitizer.sanitize(self.input, :tags => %w(b i u))
end
end

许多人建议将 includeextend作为类中的整个 helper 库,这样做有些过火。

我建议只委派您需要的帮助器方法。

比如说

class Post < ActiveRecord::Base
delegate :sanitize, to: 'ActionController::Base.helpers'
end

这将使您能够访问模型中的 sanitize