ruby-on-rails - 错误轨道中带有字段名称的字段错误过程
问题描述
我正在尝试使用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 验证错误相同)
这是 FE 验证的输出。
解决方案
如果显示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
推荐阅读
- sql-server - 如何在 mssql 服务器视图中查询访问表
- xml - 当缺少 xml 标记并提供架构时,Databricks-spark-xml 无法将不良记录过滤到不良记录列中
- c - Mac os 终端:终端窗口中的可点击文本(c 可执行文件)
- ios - Appcelerator Titanium iOS - ti.main.js 文件未找到错误
- css - Angular 7 - Autoprefixer 不适用于 CSS Grid
- javascript - 如何将动态高度和宽度设置为 HTML 表格?
- javascript - 如何在 highstock 股票图表中动态更改图表类型?
- docker - 监控 Kubernetes 资源
- swift - `运算符'<'的结果是未使用的`,而实际上它已被使用
- python - TypeError:UMat() 最多接受 2 个参数(给定 3 个)