title: Rails 3: Handle ActiveRecord::RecordNotUnique Exception
body: <p>How can I handle <code>ActiveRecord::RecordNotUnique</code> exception in the controller? Thanks</p>
  
  <p><strong>Edit</strong>: 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. </p>
  
  <pre><code>generate_code
  @couponcode = Couponcode.new(:user_id =&gt; current_user.id, :code =&gt; @code)
  </code></pre>
  
  <p><strong>Edit2</strong>:</p>
  
  <pre><code>generate_code
  
  begin
    @couponcode = Couponcode.new(:user_id =&gt; current_user.id, :code =&gt; @code)
  rescue ActiveRecord::RecordNotUnique
    #generate_code
    @code = "111-11111" 
    @couponcode = Couponcode.new(:user_id =&gt; current_user.id, :code =&gt; @code)           
  end
  </code></pre>