根据rails指南在before_add块中引发异常有很多会阻止对象添加到集合中。但是,异常提升不是由active_record处理的。
class Order < ActiveRecord::Base
belongs_to :customer
end
class Customer < ActiveRecord::Base
has_many :orders, :before_add => :check_credit_limit
def check_credit_limit(order)
#If a before_add callback throws an exception, the object does not get added to the collection.
raise 'Value cannot be greater than 450' if order.value > 450
end
end
Failure/Error: customer.orders << order
value cannot be greater than 450
我怎样才能优雅地处理这个问题?
答案 0 :(得分:0)
您可以在订单类上添加验证:
class Order < ActiveRecord::Base
validate :check_value_limit
def check_value_limit
errors.add(:value, "can not be greater than 450") if value > 450
end
end
或者作为上面marc注释的示例,您必须将错误添加到对象并手动处理异常。这是处理创建的基本示例。
更新验证方法以将错误添加到对象:
customer.rb
def check_credit_limit(order)
#If a before_add callback throws an exception, the object does not get added to the collection.
if order.value > 450
errors.add(:base, "Value can not be greater than 450")
raise 'Value cannot be greater than 450'
end
end
在控制器中处理创建异常的示例:
def create
@customer.new(params[:customer])
if @customer.save
…
else
render :action=>"new"
end
rescue
render :action=>"new"
end
您可能希望添加自定义异常类型并专门从中进行救援,以便仍然可以正确抛出任何其他异常。