ruby-on-rails - 从 Rails 中错误消息的开头删除字段名称?
问题描述
如何从错误消息的开头删除型号名称。在编写自定义消息进行验证时。我的验证是这样的:
validates :phone, presence: { message: "For security, please enter your <strong> mobile phone number </strong>" }
但是 o/p: 就像:
电话 为了安全起见,请输入您的手机号码
我想删除字段名称,即。电话从错误信息开始。我将 Ruby 2.4 与 Rails 5.2 一起使用,请使用正确的语法指导将其删除。
解决方案
您应该能够访问带有错误的哈希。用相应的列识别每个验证错误,例如:
{:phone=>["For security, please enter your <strong> mobile phone number </strong>"]}
所以从那里,你可以做errors[:phone].first
. 确保选择正确的错误消息。由于您只有一个存在验证,因此获取第一个元素就足够了,但可能会有所不同。
foo = User.new
foo.valid? # false
foo.errors
# => #<ActiveModel::Errors:0x00007f80d52ff2a8
# @base=#<User:0x00007f80d52c4bd0 id: nil, phone: nil, created_at: nil, updated_at: nil ...>,
# @details={:phone=>[{:error=>:blank}]},
# @messages={:phone=>["For security, please enter your <strong> mobile phone number </strong>"]}>
foo.errors[:phone]
# => ["For security, please enter your <strong> mobile phone number </strong>"]
foo.errors[:phone].first
# => "For security, please enter your <strong> mobile phone number </strong>"
推荐阅读
- macos - 测试 OSX 点文件
- r - 按类型从列表中删除元素
- android - 为什么我的应用在某些(而非所有)虚拟设备上启动模块活动时会崩溃?
- ruby-on-rails - Rails 部署使用 Capistrano 错误:无法提取 RVM 源
- java - 如何修复 Java 代码中 %s 的“java.util.MissingFormatArgumentException:”
- javascript - 在JS中正确使用异步和等待?
- wordpress - 无需修改,wordpress 网站上的 Pagespeed 分数每天都在下降
- r - 用 tidyverse 总结长格式数据框中的两个变量
- c# - 在手机上启动 Xamarin 应用程序时出现 Visual Studio 错误
- json - 如何检查 Redshift Spectrum 中的结构不为空?