我有一个Ride
模型,该模型带有price
浮点字段并验证精度。验证失败但无法正常显示时,我想显示自己的自定义错误消息。
根据Rails Gudes“,:message选项可让您指定验证失败时将添加到错误集合中的消息。当不使用此选项时,Active Record将为每个消息使用各自的默认错误消息验证助手。:message选项接受字符串或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/ }
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
结论:它适用于“状态”验证,不适用于数字验证,这非常令人困惑,因为文档清楚地表明您验证数字而不是状态。我对吗?这是错误还是故意的?
答案 0 :(得分:1)
我认为您出了问题的地方是期望numericality
接受验证选项format
。提到active record guides,format
没有选择。
看到您已调用此price
,看来您想将精度保持在小数点后2位,以便您可以存储某物的美元价值。正确的类型是带有scale: 2
的十进制,或者我过去已经成功使用的东西是将price
存储为整数price_in_cents
。
context 'with more than 2 digits after period' do
let(:price) { 123.333 }
it 'rounds to 2 decimal places' do
expect(subject.save).to eq true
expect(subject.reload.price).to eq 123.34
end
end
答案 1 :(得分:0)
我弄清楚了,这里有两个验证:格式验证和数字验证。我没有将消息添加到格式验证中,所以当失败时,我会收到标准消息
validates :price, format: { with: /\A\d{1,4}(.\d{0,2})?\z/, message: 'Invalid price. Max 2 digits after period'}, numericality: { message: 'is not a number' }