处理控制器中的唯一记录异常 [英] Handling Unique Record Exceptions in a Controller
问题描述
我有一个名为Subscription的模型,在[:email,:location]字段上有唯一的索引。这意味着一个电子邮件地址可以每个位置订阅。
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.
在我的模型中:
class Subscription < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true, :uniqueness => {:scope => :location}
end
在我的创建方法中。我想处理例外 ActiveRecord :: RecordNotUnique
不同于常规错误。我如何添加到这个通用的创建方法?
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
推荐答案
我不认为只有一种类型的验证失败才会有异常抛出。您可以执行 save!
,这将引发所有保存错误(包括所有验证错误)的异常,并将它们单独处理。
I don't think there is a way to have an exception thrown just for a single type of validation failure. Either you can do a save!
which would raise exceptions for all save errors (including all validation errors) and have them handled separately.
您可以做的是处理异常 ActiveRecord :: RecordInvalid
并将异常消息与进行匹配验证失败:电子邮件已被采用
然后单独处理。但是这也意味着你也必须处理其他错误。
What you can do is handle the exception ActiveRecord::RecordInvalid
and match the exception message with Validation failed: Email has already been taken
and then handle it separately. But this also means that you would have to handle other errors too.
某些东西,
begin
@subscription.save!
rescue ActiveRecord::RecordInvalid => e
if e.message == 'Validation failed: Email has already been taken'
# Do your thing....
else
format.html { render :action => 'new' }
end
end
format.html { redirect_to(root_url, :notice => 'Subscription was successfully created.') }
我不知道这是否是唯一的解决方案。
I'm not sure if this is the only solution to this though.
这篇关于处理控制器中的唯一记录异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!