注册时,我想检查控制器中是否已经存在新用户给定的电子邮件。
class LoginsController < ApplicationController
skip_before_action :verify_authenticity_token
def index
@subscriber = Subscriber.new()
end
def sign_up
subscriberNew = Subscriber.new
subscriberNew.name = params[:name]
subscriberNew.cus_user_name = params[:user_name]
subscriberNew.cus_password = params[:password]
subscriberNew.cus_email = params[:email]
subscriberNew.mobile_no = params[:phone]
#if Email exists sends and error message
#...................
#if email does not exist, save the response to database
result = subscriberNew.save
respond_to do |format|
msg = {:status => "ok", :message => "Success!"}
format.json {render :json => msg}
end
end
end
我该怎么做?
答案 0 :(得分:1)
使用uniqueness: true
https://guides.rubyonrails.org/active_record_validations.html#uniqueness
您可以执行以下操作:
class Subscriber < ApplicationRecord
validates :email, uniqueness: true
end
并执行以下操作:
subscriberNew.valid?
if subscriberNew.errors[:email].present?
#show_error
else
#success
end
我真的建议您阅读Rails命名约定,使用activerecord进行验证以及创建表单(使用form_for
帮助器和Strong Parameters https://guides.rubyonrails.org/action_controller_overview.html#strong-parameters)时的约定。
答案 1 :(得分:1)
有多种验证唯一记录的方法,更好的方法之一可能是更改数据库以为电子邮件设置唯一索引:
add_index :users, :username, unique: true
(在您的迁移中)
DB索引方法的长期性能更好(例如,请参见this)
您还可以在控制器中的before_action进行验证:
before_action :validate_email, only: [:sign_up]
...
private
def validate_email
# Or whatever way of sending a message you prefer
flash[:notice] = "A user with this email already exists"
redirect_to root_path if User.where(email: params[:email]).exists?
end
我建议在Rails Guides中进一步阅读有关Active Record验证的信息。