在我Purchase
模型中,我有一個計算稅收的方法:Rails:添加錯誤[:base]不會使記錄無效?
def calculate_tax
if self.shipping_address.state == State.new_york
corresponding_tax = Tax.find_by(zip_code: self.shipping_address.zip_code, state_id: self.shipping_address.state_id)
if corresponding_tax
self.tax = corresponding_tax.rate * (self.subtotal + shipping)
else
#HERE !!!
self.errors[:base] << "The zip code you have entered is invalid."
puts "errors = #{self.errors.full_messages}" #<-- this prints out the error in my log, so I know it's being run
end
else
self.tax = 0.00
end
end
這種方法被調用此方法中:
def update_all_fees!
calculate_subtotal
calculate_shipping
calculate_tax #<-- being called here
calculate_total
save!
end
然而,save!
成功地保存記錄。它不應該拋出異常嗎?我將如何讓它保存! calculate_tax在第二個else
區塊時失敗?
驗證郵政編碼將無濟於事。我沒有驗證Tax模式,我試圖查看給定的郵政編碼是否有匹配的稅收記錄。 – Edmund
啊,我看到了。然後@ JorgedelosSantos的答案應該能夠幫助你。 – MCBama