【问题标题】:Checking if the email had been already taken in the following if statement (Rails)?检查电子邮件是否已在以下 if 语句(Rails)中被接收?
【发布时间】:2012-10-26 00:16:07
【问题描述】:

我有以下操作:

users.rb:

  def omniauth_create
    auth = request.env["omniauth.auth"]
    user = User.from_omniauth(env["omniauth.auth"])
    unless user.email.blank?
      if user.id.nil?
        # Save the user since he hasn't been created yet
        user.save!
      end
      sign_in user
      redirect_back_or user
    else
      # Send user to a form to fill his email
      #session[:omniauth] = request.env['omniauth.auth'].except('extra')
      redirect_to(enter_email_path(oprovider: user.provider,
                                   ouid: user.uid,
                                   oname: user.name,
                                   opassword: user.password,
                                   opassword_confirmation: user.password))
    end
  end

它执行以下操作:

  • 如果用户的email 不为空,请让他登录,然后将他重定向到他的个人资料(如果他的id 是nil,则保存他。换句话说,如果他还没有被创建) .
  • 如果用户的email 为空白,请将其发送至enter_email_path(用户可以在其中输入他的电子邮件)。

现在我想添加另一个 if 语句,如果 email 已被占用,则会闪烁错误,并将用户重定向到 root_path

我不太确定该怎么做,有什么建议吗? (以及将 if 语句放在哪里?)

编辑:

奇怪,得到了这个而不是重定向到根路径:

Validation failed: Email has already been taken

我不知道这是否有帮助,但这是 from_omniauth 的来源:

  def self.from_omniauth(auth)
    find_by_provider_and_uid(auth["provider"], auth["uid"]) || User.create_with_omniauth(auth)
  end

  def self.create_with_omniauth(auth)
    new do |user|
      user.provider = auth["provider"]
      user.uid = auth["uid"]
      user.name = auth["info"]["name"]
      user.email = auth["info"]["email"]
      user.password = user.password_confirmation = SecureRandom.urlsafe_base64(n=6) 
    end
  end

现在的代码:

user.rb:

# if user.email.present?
  if user.id.nil?
    # User.find_by_email(user.email).present?
    if User.exists?(:email => user.email)
      redirect_to root_path
    end
    user.save!
  end
  sign_in user
  redirect_back_or user
else

(其余不变)。

似乎代码忽略了if User.exists?(:email => user.email) 部分?

【问题讨论】:

    标签: ruby-on-rails ruby if-statement omniauth


    【解决方案1】:

    Rails 有一个方法可以根据参数检查对象exists。你可以这样做:

    if user.email.present?
      if user.id.nil?
        if User.exists?(:email => user.email)
          # return redirect email is already token
        end
    
        # save user
      end
      # sign_in user
    else
      # redirect to get email
    end
    

    顺便说一句,我不熟悉 Omniauth,所以我不确定什么是正确的,但 new_record? 通常用于检查对象是否已保存。如果您有 id,通常是。
    如果您感到困惑,您可以在 User 模型中创建函数以便更好地阅读,例如

    class User
      def new?
        id.nil?
      end
    
      def email_taken?
        self.class.exists?(:email => email)
      end
    end
    
    # back to controller
    if user.email.present?
      if user.new?
        if user.email_taken?
          # return redirect email is already token
        end
    
        # save user
      end
      # sign_in user
    else
      # redirect to get email
    end
    

    【讨论】:

    • 非常感谢!但我收到了Validation failed: Email has already been taken(请参阅我的编辑)。
    • @alexchenco 我没有在email_taken? 之后随机写return。您想退出该功能,不想保存此用户。所以你应该在这里使用return redirect_to root_path。
    • @redirect_back_or user 哦,抱歉,没看到。我忘记了 return 在 Ruby 中做了什么。谢谢!对了,为什么redirect_back_or user不需要return?
    • @alexchenco 因为这是函数的结尾,此后不会执行其他代码。如果你愿意,你可以添加它,但这不会改变任何东西。在 ruby​​ 中,函数执行的最后一条语句会自动返回。
    • 哦,我明白了,我正在寻找“结束”作为if 的结束。没有将else 视为“结束”。再次感谢!
    【解决方案2】:

    试试这个

     def omniauth_create
        auth = request.env["omniauth.auth"]
        user = User.from_omniauth(env["omniauth.auth"])
        if user.email.present?
          if user.id.nil?
            if User.find_by_email(user.email).present?
              # send error email already be taken
              # or login with that user that means define that user for sign in
            else
              # save user and login with that user
              user.save!  
            end
            sign_in user
            redirect_back_or user
          end 
        else
          # Send user to a form to fill his email
          # session[:omniauth] = request.env['omniauth.auth'].except('extra')
          redirect_to(enter_email_path(oprovider: user.provider,
                                       ouid: user.uid,
                                       oname: user.name,
                                       opassword: user.password,
                                       opassword_confirmation: user.password))
    
        end
    

    更新

    你也可以使用find_or_create方法

    def self.find_or_create(attributes)
      Model.where(attributes).first || Model.create(attributes)
    end
    

    更新 2

    在你的模态文件中

      class << self
        def create_with_omniauth(auth)
          create! do |user|
            user.provider = auth['provider']
            user.uid = auth['uid']
            if auth['info']
              user.uid = auth['uid'] || ""
              user.name = auth['info']['name'] || ""
              user.email = auth['info']['email'] || ""
              user.access_token = auth['credentials']['token'] || ""
              user.oauth_token_secret = auth['credentials']['secret'] || ""
              user.oauth_token = auth['credentials']['token'] || ""
            end
          end
        end
      end
    

    在你的控制器中

      def create
        auth = request.env["omniauth.auth"]
        user = User.where(:provider => auth['provider'],:uid => auth['uid']).first || User.create_with_omniauth(auth)
        session[:user_id] = user.id
        redirect_to root_url 
      end
    

    【讨论】:

    • 谢谢!但是得到了这个:Validation failed: Email has already been taken (please see my EDIT).
    • 谢谢!但我很困惑,你是想把它放在我的create 行动或omniauth_create 行动中吗?编辑:但是如果电子邮件和密码为空,那么我会收到错误消息?
    • 是的,我知道了:Validation failed: Email can't be blank, Email is invalid, Password confirmation can't be blank:
    【解决方案3】:

    不确定您想要的是 rails 答案还是 SQL 答案,但您可以使用以下 SQL 来查找您的回复:

    select id from users where email = :email 
    

    如果返回 0 行,则电子邮件不存在,如果返回 1,则存在。我想你也可以使用

    Users#find(:first, :conditions => 'email = #{email}') 
    

    但我还没有测试过。

    【讨论】:

    • Rails 答案。我想把它放在控制器中(但 if 语句让我感到困惑)。
    • 不应该是Users.find(:first, :conditions =&gt; 'email = #{user.email}')吗?对不起,如果我弄错了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-04
    相关资源
    最近更新 更多