提问人:Starscream512 提问时间:6/30/2023 最后编辑:Starscream512 更新时间:7/1/2023 访问量:33
(Ruby on Rails validates_confirmation_of)如何将错误消息切换到确认字段?
(Ruby on Rails validates_confirmation_of) How to switch error message to the confirmation field?
问:
在 Ruby on Rails 3.2 中,我尝试使用以下命令来验证密码确认:
validates_confirmation_of :password
Rails 会将验证错误添加到该字段。如何将验证错误添加到字段中?:password
:password_confirmation
答:
0赞
smathy
6/30/2023
#1
你使用的是哪个版本的 Rails?它应该将错误添加到属性中::password_confirmation
[9] pry(main)> class Foo < ApplicationRecord; attribute :password; validates_confirmation_of :password; end
=> [ActiveModel::Validations::ConfirmationValidator]
[10] pry(main)> ff = Foo.new(password: "foo", password_confirmation: "bar"); ff.validate
=> false
[11] pry(main)> ff.errors
=> #<ActiveModel::Errors [#<ActiveModel::Error attribute=password_confirmation, type=confirmation, options={:attribute=>"Password"}>]>
[12] pry(main)> ff.errors[:password_confirmation]
=> ["doesn't match Password"]
剧情转折:OP 揭示了它的 Rails 3.2
我可能会在我的控制器中添加(类似的东西):
if @model.errors.added? :password, :confirmation
@model.errors.add :password_confirmation, :confirmation
@model.errors.delete :password, :confirmation
end
评论
0赞
Starscream512
6/30/2023
我正在使用 Rails 3.2。对于 Rails 4 及更高版本,您的答案是正确的,但我需要它才能适用于早期版本。
0赞
Schwern
6/30/2023
@Starscream512 那是 10 岁了。我猜升级是不可能的?
评论