Rails 3: Handle ActiveRecord::RecordNotUnique Exception

后端 未结 3 1768
臣服心动
臣服心动 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

    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.

提交回复
热议问题