首页 > 解决方案 > 从 Rails 中错误消息的开头删除字段名称?

问题描述

如何从错误消息的开头删除型号名称。在编写自定义消息进行验证时。我的验证是这样的:

validates :phone, presence: {  message: "For security, please enter your <strong> mobile phone number </strong>" }

但是 o/p: 就像:

电话 为了安全起见,请输入您的手机号码

我想删除字段名称,即。电话从错误信息开始。我将 Ruby 2.4 与 Rails 5.2 一起使用,请使用正确的语法指导将其删除。

标签: ruby-on-railsdeviseruby-on-rails-5ruby-2.4

解决方案


您应该能够访问带有错误的哈希。用相应的列识别每个验证错误,例如:

{: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>"

推荐阅读