【发布时间】:2018-11-18 10:15:14
【问题描述】:
我有一个 Ride 模型,带有 price 浮点字段和精度验证。当验证失败但它不起作用时,我想显示我自己的自定义错误消息。
根据Rails Gudes“:message 选项让您指定验证失败时将添加到错误集合中的消息。当不使用此选项时,Active Record 将为每个验证助手使用各自的默认错误消息. :message 选项接受 String 或 Proc。"
我完全按照那里的示例进行操作,但它不起作用。
导轨
validates :age, numericality: { message: "%{value} seems wrong" }
我的例子
validates :price, numericality: { message: "Invalid price. Max 2 digits after period"}, format: { with: /\A\d{1,4}(.\d{0,2})?\z/ }
spec/models/ride_spec.rb
context 'with more than 2 digits after period' do
let(:price) { 29.6786745 }
it 'the price is invalid' do
expect(subject.save).to be_falsy
expect(subject).not_to be_persisted
puts subject.errors.full_messages.last # "Price is invalid"
end
end
我做错了什么?
更新
这是我到目前为止所学到的。 我在测试中将价格设置为空,现在它会显示我想要的错误消息。
context 'with more than 2 digits after period' do
let(:price) { '' }
it 'the price is invalid' do
expect(subject.save).to be_falsy
expect(subject).not_to be_persisted
puts subject.errors.full_messages.last # "Price Invalid price. Max 2 digits after period"
end
end
结论:它适用于“存在”验证,而不适用于数字验证,这非常令人困惑,因为文档清楚地说您验证的是数字,而不是存在。我对吗?这是一个错误还是故意的?
【问题讨论】: