您应该能够访问带有错误的哈希。用相应的列识别每个验证错误,例如:
{: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>"