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
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
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With