在 Rails 控制器中使用 sanitize

发布于 2024-09-28 14:12:25 字数 484 浏览 6 评论 0原文

我正在尝试在控制器内调用 sanitize 。这是我尝试过的:

class FooController < ApplicationController
  include ActionView::Helpers::SanitizeHelper
  # ...
end

但是,我收到此错误:

undefined method `white_list_sanitizer' for FooController:Class

我四处搜索,人们建议切换包含行以包含 ActionView::Helpers,但这会导致此错误:

undefined method `url_for' for nil:NilClass

什么是正确的方法调用清理?我正在使用 Rails 2.3.5。

I'm trying to call sanitize within a controller. Here's what I tried:

class FooController < ApplicationController
  include ActionView::Helpers::SanitizeHelper
  # ...
end

However, I'm getting this error:

undefined method `white_list_sanitizer' for FooController:Class

I searched around and people recommended switching the include line to include ActionView::Helpers, but that results in this error:

undefined method `url_for' for nil:NilClass

What's the correct way to call sanitize? I'm using Rails 2.3.5.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

败给现实 2024-10-05 14:12:25

您可以在操作方法中使用此 ActionController::Base.helpers

class SiteController < ApplicationController
  def index
    render :text => ActionController::Base.helpers.sanitize('<b>bold</b>')
  end
end

希望这会有所帮助

you can use this ActionController::Base.helpers inside action method:

class SiteController < ApplicationController
  def index
    render :text => ActionController::Base.helpers.sanitize('<b>bold</b>')
  end
end

Hope this helps

只有影子陪我不离不弃 2024-10-05 14:12:25

Rails 6:

要从文本中删除链接(例如),只需调用:

...
Rails::Html::LinkSanitizer.new.sanitize("links here will be stripped")
...

请参阅 https://github .com/rails/rails-html-sanitizer

Rails 6:

To strip links (for example) from a text, just call:

...
Rails::Html::LinkSanitizer.new.sanitize("links here will be stripped")
...

see https://github.com/rails/rails-html-sanitizer

对不⑦ 2024-10-05 14:12:25

我不确定你想在这里做什么,但我几乎 100% 确定它不属于控制器。

如果您想在将属性保存到数据库之前对其进行清理,请在模型中使用保存前回调来执行此操作。

否则,请在视图模板或视图助手中进行清理。

I'm not sure what you're trying to do here but I'm almost 100% certain it doesn't belong in the controller.

If you want to sanitize an attribute before you save it to the DB, do so in the model with a before save callback.

Otherwise, sanitize in the view template or view helper.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文