我有一个名为Subscription的模型,它在字段[:email,:location]上有唯一索引.这意味着每个位置可以订阅一个电子邮件地址.
在我的模型中:
class Subscription < ActiveRecord::Base
validates :email, :presence => true, :uniqueness => true, :email_format => true, :uniqueness => {:scope => :location}
end
Run Code Online (Sandbox Code Playgroud)
在我的创建方法中.我想以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
Run Code Online (Sandbox Code Playgroud)