Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Unique Record Exceptions in a Controller

I have a model called Subscription that has a unique index on the fields [:email, :location]. This means one email address can subscribe per location.

In my model:

class Subscription < ActiveRecord::Base
  validates :email, :presence => true, :uniqueness => true, :email_format => true, :uniqueness => {:scope => :location}
end

In my create method. I want to handle the the exception ActiveRecord::RecordNotUnique differently than a regular error. How would I add that in to this generic create method?

  def create
    @subscription = Subscription.new(params[:subscription])
    respond_to do |format|
      if @subscription.save
        format.html { redirect_to(root_url, :notice => 'Subscription was successfully created.') }
      else
        format.html { render :action => 'new' }
      end
    end
  end
like image 801
Dex Avatar asked Feb 13 '11 04:02

Dex


2 Answers

This gem rescues the constraint failure at the model level and adds a model error (model.errors) so that it behaves like other validation failures. Enjoy! https://github.com/reverbdotcom/rescue-unique-constraint

like image 99
Yan Pritzker Avatar answered Sep 30 '22 04:09

Yan Pritzker


You will want to use rescue_from

In your controller

 rescue_from ActiveRecord::RecordNotUnique, :with => :my_rescue_method

 ....

 protected

 def my_rescue_method
   ...
 end

However, wouldn't you want to invalidate your record rather than throwing an exception?

like image 29
The Who Avatar answered Sep 30 '22 04:09

The Who