“已发送电子邮件”redirect_to登录页面

时间:2017-06-05 02:46:48

标签: ruby-on-rails validation model-view-controller

如果验证失败......

user.rb

  validates :name,  presence: true, length: { maximum: 20 }
  validates :last_name,  presence: true, length: { maximum: 20 }
  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password

因为“已经使用电子邮件”,用户应该被重定向到sessions/new以登录,否则users/new页面应该刷新,并显示相应的错误消息,例如“密码不能为空”。 / p>

users_controller

  if # How to make conditional work where if email is already taken do this...
    flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
    render 'sessions/new'
  else
    render 'new'
  end

用户发送已存在的电子邮件...

Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"teFpI/xcFe4Ngdtcj8+7DEj+3ipMBObjzBjs143ILQ/bpefsZSuWWh7cxKJJRXqmCAW+35/H9UPKB56SDdO+6A==", "user"=>{"name"=>"test", "last_name"=>"mon", "email"=>"testmonkey@gmail.com", "password"=>"[FILTERED]", "time_zone"=>"Eastern Time (US & Canada)", "subscribe"=>"0"}, "button"=>""}
   (0.2ms)  BEGIN
  User Exists (0.5ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER('testmonkey@gmail.com') LIMIT 1
   (0.2ms)  ROLLBACK
  Rendered sessions/new.html.erb within layouts/application (2.0ms)
  Rendered layouts/_header.html.erb (1.4ms)
Completed 200 OK in 496ms (Views: 159.6ms | ActiveRecord: 4.7ms)

user.rb

  validates :name,  presence: true, length: { maximum: 20 }
  validates :last_name,  presence: true, length: { maximum: 20 }
  validates :email, presence: true, length: { maximum: 255 }, uniqueness: { case_sensitive: false }, unless: -> { from_omniauth? }
  has_secure_password

2 个答案:

答案 0 :(得分:1)

我会做这样的事情:

ContainerControlledLifetimeManager

答案 1 :(得分:1)

在现有记录中查找电子邮件时,您可以检查find_by_email是否返回与nil不同的内容:

if User.find_by(email: params[:user][:email])
  flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
  render 'sessions/new'
else
  render 'new'
end

或者如果您想更具体,可以使用ActiveRecord#exists?

if User.exists?(email: params[:user][:email])
  flash[:alert] = "EMAIL ALREADY TAKEN. LOG IN WITH EMAIL"
  render 'sessions/new'
else
  render 'new'
end