我有一个名为 Subscription 的模型,它在字段 [:email, :location] 上有唯一的索引。这意味着每个位置都可以通过一个电子邮件地址进行订阅。
在我的模型中:
class Subscription < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true, :uniqueness => {:scope => :location}
end
在我的创建方法中。我想处理异常ActiveRecord::RecordNotUnique
与常规错误不同。我如何将其添加到这个通用创建方法中?
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!
这会引发所有保存错误(包括所有验证错误)的异常,并单独处理它们。
你能做的就是处理异常ActiveRecord::RecordInvalid
并将异常消息与Validation failed: Email has already been taken
然后分别处理。但这也意味着您还必须处理其他错误。
就像是,
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.') }
我不确定这是否是唯一的解决方案。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)