首页 > 解决方案 > 错误轨道中带有字段名称的字段错误过程

问题描述

我正在尝试使用field_error_proc. 但我找不到用字段名称添加错误的方法。下面是我用来在 Rails 中生成包含错误的字段的代码。

ActionView::Base.field_error_proc = proc do |html_tag, instance|
  if html_tag =~ /^<label/
    %(#{html_tag}).html_safe
  else
    %(#{html_tag}<div class="help-block"><ul role="alert"><li>#{instance.error_message.first}</li></ul></div>).html_safe
  end
end

下面是上述代码的输出。我想要的是出现“需要电子邮件”之类的字段名称错误,以便具有常见的错误模式(与 FE 验证错误相同)

使用字段错误 proc 生成的错误以进行存在验证

这是 FE 验证的输出。

在此处输入图像描述

标签: ruby-on-railsruby-on-rails-5actionview

解决方案


如果显示instance块参数的内容,您应该会看到如下内容:

#<ActionView::Helpers::Tags::TextField:0x00007f54102118d8 @method_name="email", @object_name="user" # ...(more)

因此,为了获取经过验证的输入的方法名称,您可以使用:

ActionView::Base.field_error_proc = proc do |html_tag, instance|
  method_name = instance.instance_variable_get("@method_name").humanize
  if html_tag =~ /^<label/
    %(#{html_tag}).html_safe
  else
    %(#{html_tag}<div class="help-block"><ul role="alert"><li>#{method_name} #{instance.error_message.first}</li></ul></div>).html_safe
  end
end

推荐阅读