如何处理控制器中的ActiveRecord :: RecordNotUnique异常?谢谢
编辑:当生成唯一代码时,我收到该异常.我可以处理application_controller.rb中的异常,但我真正想要的是重新生成代码,必须在控制器中完成.
generate_code @couponcode = Couponcode.new(:user_id => current_user.id,:code => @code)
EDIT2:
generate_code begin @couponcode = Couponcode.new(:user_id => current_user.id,:code => @code) rescue ActiveRecord::RecordNotUnique #generate_code @code = "111-11111" @couponcode = Couponcode.new(:user_id => current_user.id,:code => @code) end
解决方法
begin # do stuff rescue ActiveRecord::RecordNotUnique # handle the exception however you want to end
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html
如果你需要经常处理的话,你也可以使用rescue_from
.