将项目添加到 has_many 集合时进行限制
根据 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
我怎样才能优雅地处理这个问题?
According to rails guide raising an exception in the before_add block for has many will prevent the object getting added to the collection. But however the exception raise is not handled by 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
How can i handle this gracefully?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以在订单类上添加验证:
或者作为上面 marc 注释的示例,您必须将错误添加到您的对象并手动处理异常。这是处理创建的基本示例。
更新您的验证方法以将错误添加到对象:
customer.rb
处理控制器中创建时的异常的示例:
您可能需要添加自定义异常类型并专门从中进行救援,以便仍然可以正确抛出任何其他异常。
You can add the validation on the order class:
OR as an example for marc's comment above, you'll have to add the error to your object and handle the exception manually. This is a basic example of handling on a create.
update your validation method to add the error to the object:
customer.rb
an example of handling the exception on create in your controller:
You may want to add a custom exception type and rescue from it specifically so any other exceptions will still be thrown correctly.