gpt4 book ai didi

ruby-on-rails - rails : Adding to errors[:base] does not make record invalid?

转载 作者:行者123 更新时间:2023-12-04 06:06:15 24 4
gpt4 key购买 nike

在我的 Purchase模型,我有一种计算税收的方法:

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 时失败堵塞?

最佳答案

您可以使用 validate 添加自定义验证方法。指示。以下可能采用您发布的代码:

class Purchase < ActiveRecord::Base
validate :new_york_needs_tax_record

def update_all_fees!
calculate_subtotal
calculate_shipping
calculate_tax
calculate_total
save!
end

private

def calculate_tax
if ships_to_new_york? && corresponding_tax
self.tax = corresponding_tax.rate * (self.subtotal + shipping)
elsif !ships_to_new_york?
self.tax = 0.00
else
self.tax = nil
end
end

def ships_to_new_york?
self.shipping_address.state == State.new_york
end

def corresponding_tax
Tax.find_by(zip_code: self.shipping_address.zip_code, state_id: self.shipping_address.state_id)
end

def new_york_need_tax_record
if ships_to_new_york? && !corresponding_tax
self.errors[:base] << "The zip code you have entered is invalid."
end
end
end

关于ruby-on-rails - rails : Adding to errors[:base] does not make record invalid?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24149595/

24 4 0
文章推荐: ruby-on-rails - Ruby 数据结构呈现某种 JSON 格式
文章推荐: windows-8 - 在 Windows 8 应用程序中保存 List 的最佳方法是什么