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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:01:06  来源:igfitidea点击:

Rails 3: Handle ActiveRecord::RecordNotUnique Exception

ruby-on-railsruby-on-rails-3

提问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

Using this validation method validate_uniqueness_ofdoes not guarantee the absence of duplicate record insertions.

使用这种验证方法validate_uniqueness_of并不能保证不存在重复的记录插入。

You should look here

你应该看看这里

回答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 并且它在没有检查的情况下是唯一的。