Rails - 在错误过程中转义JavaScript

时间:2012-10-11 02:29:35

标签: ruby-on-rails ruby ruby-on-rails-3

我有一个自定义错误proc,它在 application.rb 中初始化:

config.action_view.field_error_proc = Proc.new do |html_tag, object|
  error_msg = object.error_message.join(", ")
  "<span class='field_with_errors' data-error='#{error_msg}'>#{html_tag}</span>".html_safe
end

我想逃避javascript,所以我修改它:

config.action_view.field_error_proc = Proc.new do |html_tag, object|
  error_msg = object.error_message.join(", ")
  "<span class='field_with_errors' data-error='#{escape_javascript(error_msg)}'>#{html_tag}</span>".html_safe
end

但是我收到以下错误:

undefined method `escape_javascript' for #<MyApp::Application:0x00000006edd2e8>

我正在使用 rails 3.0

任何提示都将不胜感激。

1 个答案:

答案 0 :(得分:3)

您必须包含帮助程序才能使其可用。这应该有效:

include ActionView::Helpers::JavaScriptHelper

config.action_view.field_error_proc = Proc.new do |html_tag, object|
  error_msg = object.error_message.join(", ")
  "<span class='field_with_errors' data-error='#{escape_javascript(error_msg)}'>#{html_tag}</span>".html_safe
end