Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3: Handle ActiveRecord::RecordNotUnique Exception

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
like image 542
donald Avatar asked Jan 05 '11 21:01

donald


2 Answers

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.

like image 121
idlefingers Avatar answered Oct 13 '22 20:10

idlefingers


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

You should look here

like image 36
Olegykz Avatar answered Oct 13 '22 20:10

Olegykz