[英]How to return success for .save() even if record also exists? — Rails 3.1
I'm trying to modify the following code to make it return the flash notice and success if the email
exists. 我正在尝试修改以下代码,以使其返回闪回通知和成功(如果存在
email
。
class SubscribersController < ApplicationController
respond_to :json
def create
@subscriber = Subscriber.new(:first_name => params[:first_name],
:last_name => params[:last_name],
:email => params[:email],
:ip_address => request.remote_ip,
:referring_page => request.referer )
if @subscriber.save
flash[:notice] = "You've been subscribed!"
end
respond_with(@subscriber)
end
end
How could I check if the email address exists already and return success with the flash message? 如何检查电子邮件地址是否已经存在并通过Flash消息返回成功?
I don't want to throw an error if the email already exists (which the model checks for) -- I want to still say you've been subscribed. 如果电子邮件已经存在(模型检查该电子邮件),我不想抛出错误-我仍然想说您已订阅。
I've tried checking with .present?
我试着用
.present?
检查.present?
but it throws an error: 但是它抛出一个错误:
<h1>
NoMethodError
in SubscribersController#create
</h1>
<pre>undefined method `model_name' for ActiveRecord::Relation:Class</pre>
I believe, you could use a dynamic finder for this matter. 我相信,您可以为此使用动态查找器。
@subscriber = Subscriber.find_or_initialize_by_email(params[:email], { :first_name => ..., })
however, I think, saving a persisted record will return false
, so you need to check if 但是,我认为保存持久记录将返回
false
,因此您需要检查是否
@subscriber.persisted? or @subscriber.save
flash[:success] = "You've been subscribed!"
end
Add a validation in de subscriber model 在用户模型中添加验证
validates_uniqueness_of :email
and in the controller 并在控制器中
@subscriber.valid?
if @subscriber.errors.on(:email) == "XXX"
flash[:error] = "email address exists already"
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.