我正在尝试使用我的用户控制器在他们的电子邮件已用于注册时通知用户,但即使电子邮件已经存在,我仍然收到错误“请验证您的输入并重试”,而不是“你已经注册了!谢谢你的热情!” 使用控制器不是实现此行为的创建方式吗?
在 Rails 控制台中(假设“foo@bar.com”在数据库中),当我使用它user = User.new(name:"Example", email:"foo@bar.com")
时User.find_by_email(user.email)
,它确实返回了正确的用户条目,所以我不确定我是否在正确的轨道上并且只是执行它不正确或什么。有什么想法吗?
users_controller.rb:
class UsersController < ApplicationController
def new
@user = User.new(params[:user])
end
def create
@user = User.new(params[:user])
if @user.save
flash[:success] = "Thanks for supporting cofind! We'll be in touch!"
redirect_to root_path
UserMailer.welcome_email(@user).deliver
else
if @user.email == User.find_by_email(@user.email)
flash[:error] = "You've already registered! Thanks for being enthusiastic!"
redirect_to root_path
else
flash[:error] = "Plase validate your input and try again."
redirect_to signup_path
end
end
end
end
用户.rb:
class User < ActiveRecord::Base
attr_accessible :email, :name
before_save { |user| user.email = email.downcase }
validates :name, presence: true
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
end