字段名称错误字段中的字段错误proc

时间:2020-07-19 07:14:51

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

我正在尝试使用field_error_proc在rails中添加字段错误。但是我找不到一种使用字段名称添加错误的方法。下面是我用来生成带有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
下面的

是上面代码的输出。我想要的是在字段名称中出现一个错误,例如“ Email is required”,以便具有常见的错误模式(与FE验证错误相同)

Error generated with field error proc for presence validation

这是有限元验证的输出。

enter image description here

1 个答案:

答案 0 :(得分:0)

如果您显示 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
相关问题