Reputation: 11
I'm new to Rails, and am trying to create a signup form for my site. 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
Upvotes: 1
Views: 1289
Reputation: 107037
It does work, because the user's email address is not passed properly. That could be fixed by changing @user.exists?(:username)
to @user.exists?(params[:username])
.
But Ruby on Rails includes such validations, and you do not need to write them on your own. Use Rails present and uniqueness validations like this:
# in your user.rb
validates :username, presence: true, uniqueness: true
You might want to ignore upper and lower case:
# in your user.rb
validates :username, presence: true, uniqueness: { case_sensitive: false }
And change your create
method to this:
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
Upvotes: 5
Reputation: 242
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])
Upvotes: 0
Reputation: 9700
As suggested, you should use model validation for something like this. However, here's why your code doesn't work.
The 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
Upvotes: 1
Reputation: 7777
Use like this in the model file such as
validates_uniqueness_of :username #=> or specify :email or :name etc...
Upvotes: 1