Ruby-on-rails Rails 3:处理 ActiveRecord::RecordNotUnique 异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4609531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails 3: Handle ActiveRecord::RecordNotUnique Exception
提问by donald
How can I handle ActiveRecord::RecordNotUniqueexception in the controller? Thanks
如何处理ActiveRecord::RecordNotUnique控制器中的异常?谢谢
Edit: I'm getting that exception when generating an unique code. I can handle the exception in the application_controller.rb but what I really want is to code to be generated again and that must be done in the controller.
编辑:生成唯一代码时出现该异常。我可以处理 application_controller.rb 中的异常,但我真正想要的是再次生成代码,并且必须在控制器中完成。
generate_code
@couponcode = Couponcode.new(:user_id => current_user.id, :code => @code)
Edit2:
编辑2:
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
回答by idlefingers
begin
# do stuff
rescue ActiveRecord::RecordNotUnique
# handle the exception however you want to
end
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html
http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html
You could also use rescue_fromif it's something you need to deal with often.
rescue_from如果您需要经常处理它,您也可以使用它。
回答by Olegykz
回答by Brian Deterling
You can add a uniqueness validation and still have a chance to change the code without having to use rescue.
您可以添加唯一性验证,并且仍然有机会更改代码而无需使用救援。
couponcode.rb
优惠券代码.rb
validates_uniqueness_of :code
controller:
控制器:
@couponcode = Couponcode.new(:user_id => current_user.id)
begin
couponcode.code = generate_code
# might want to break out after a limit here
end until @couponcode.valid?
@couponcode.save
But you could also use a uuid and it would be unique without a check.
但是您也可以使用 uuid 并且它在没有检查的情况下是唯一的。

