How can I handle ActiveRecord::RecordNotUnique
exception in the controller? Thanks
Edit: I\'m getting that exception when generating an
Using this validation method validate_uniqueness_of does not guarantee the absence of duplicate record insertions.
You should look here
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.
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.