Rails 3: Handle ActiveRecord::RecordNotUnique Exception

后端 未结 3 1745
臣服心动
臣服心动 2020-12-28 18:31

How can I handle ActiveRecord::RecordNotUnique exception in the controller? Thanks

Edit: I\'m getting that exception when generating an

相关标签:
3条回答
  • 2020-12-28 18:41

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

    You should look here

    0 讨论(0)
  • 2020-12-28 18:41

    You can add a uniqueness validation and still have a chance to change the code without having to use rescue.

    couponcode.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.

    0 讨论(0)
  • 2020-12-28 19:03
    begin
      # do stuff
    rescue ActiveRecord::RecordNotUnique
      # handle the exception however you want to
    end
    

    http://ruby-doc.org/docs/ProgrammingRuby/html/tut_exceptions.html

    You could also use rescue_from if it's something you need to deal with often.

    0 讨论(0)
提交回复
热议问题