简体   繁体   English

“存在?”方法不起作用-在保存到数据库之前尝试检查用户是否存在

[英]“exists?” method not working- trying to check if a user exists before saving to DB

I'm new to Rails, and am trying to create a signup form for my site. 我是Rails的新手,正在尝试为我的网站创建一个注册表单。 It works fine, with one exception- it saves users to the database without checking first to see if they exist. 它工作正常,但有一个例外-将用户保存到数据库中,而无需先检查用户是否存在。 How can I check to make sure a user exists before I save it? 在保存用户之前,我该如何检查以确保用户存在?

User controller: 用户控制器:

class UsersController < ApplicationController
  def new
    @user = User.new
  end

  def create 
    @user = User.new(user_params)
    if @user.exists?(:username) == false && @user.save(user_params)
      session[:id] = @user.id
      redirect_to posts_path
    else
      redirect_to '/signup'
    end
  end

  def edit

  end

  def update
  end

  def show
  end

  def destroy
  end

    private

  def user_params
    params.require(:user).permit(:username, :jabber_id, :password)
  end
end

A very simple validation would be something like this: 一个非常简单的验证将是这样的:

# in your user.rb
validates :username, uniqueness: true

You might want to ignore upper and lower case: 您可能要忽略大小写:

# in your user.rb
validates :username, uniqueness: { case_sensitive: false }

And change your create method to something like this: 并将您的create方法更改为如下所示:

def create 
  @user = User.new(user_params)

  if @user.save 
    session[:id] = @user.id
    redirect_to posts_path
  else
    render :new
  end
end

Furthermore, I suggest having a unique index on the database level too: 此外,我建议在数据库级别也有一个唯一索引:

# in a migration
add_index :users, :username, unique: true

在模型文件中使用这样的文件,例如

validates_uniqueness_of :username #=> or specify :email or :name etc...

As suggested, you should use model validation for something like this. 如建议的那样,您应该对此类使用模型验证。 However, here's why your code doesn't work. 但是,这就是您的代码不起作用的原因。

The exists? exists? method is to be used on the model class, not an instance of it for example: 方法将用于模型类,而不是其实例,例如:

Person.exists?(5)
Person.exists?(:name => "David")

The above is from the exists? 以上是从存在吗? docs docs

As almost people suggested you above and this is the best way to use uniqueness validation. 正如上面的几乎所有人所建议的那样,这是使用唯一性验证的最佳方法。

But, If you want to give it a try with exists? 但是,是否要尝试使用存在? You can do like, 你可以喜欢

User.exists?(username: params[:username]) User.exists?(用户名:params [:username])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM