Prox
Prox

Reputation: 759

How do I check if name or email exists and if it does, stop current action? Ruby on Rails

I set up authentication using this guide... https://gist.github.com/thebucknerlife/10090014

I want to verify if name or email already exists. If it does not exist, I want it to go ahead and create user. If it does exist, I want it to stop and do something else.

I do not want to create duplicate users.

I set up a model with this: rails generate model user name email password_digest

I have this in my users controller:

  def create
    user = User.new(user_params)
    if user.save
      session[:user_id] = user.id
      redirect_to '/'
    else
      redirect_to '/signup'
    end
  end

Here is my /users/new.html.erb

Signup!

<%= form_for :user, url: '/users' do |f| %>

  Name: <%= f.text_field :name %>
  Email: <%= f.text_field :email %>
  Password: <%= f.password_field :password %>
  Password Confirmation: <%= f.password_field :password_confirmation %>
  <%= f.submit "Submit" %>

<% end %>

I have tried some things like this in my users controller with no luck:

  def create
    if Users.where?(:name => user)
      redirect_to 'articles'
    else
      user = User.new(user_params)
      if user.save
        session[:user_id] = user.id
        redirect_to '/'
      else
        redirect_to '/signup'
      end
    end
  end

Upvotes: 1

Views: 3290

Answers (2)

spickermann
spickermann

Reputation: 107037

Might be worth it noting that validates :email, uniqueness: true only works if it is the only validation in your model.

If you, for example, ask for a nickname too and require the nickname to be present (validates :nickname, presence: true) than the validation might fail, because the nickname is missing although the email is unique. That might lead to unexpected behavior.

I recommend using a uniqueness validation in your model, just to be safe. But to answer if a user with a certain email already exists, I would suggest asking the User model exactly that:

if User.exists?(email: params[:user][:email])
  # ...

Upvotes: 3

ydaniju
ydaniju

Reputation: 400

All you need to do is to validate email ensuring uniqueness true. By so doing, any attempt to create a user with that email will throw an error.

Add to your user model:

validates_uniqueness_of :email or validates :email, uniqueness: true

Upvotes: 2

Related Questions