Alex Rivera | Logout

Rails 3: Handle ActiveRecord::RecordNotUnique Exception

Asked 2011-01-05T21:44:29.347
16

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

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.

generate_code
@couponcode = Couponcode.new(:user_id => current_user.id, :code => @code)

Edit2:

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
Edit
Report

1 Answer

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

answered 2011-01-05T21:57:49.523

Your Answer