1

I am creating a simple user registration functionality and making user input firstname, lastname and email. Email field should be unique for all users. I have given this constraint in db. In code though, when a row with duplicate email is input, it does not create a row in db but does not raise any exception too. I am stuck on how to show error to user.

My code:
table creation script:
CREATE TABLE customers (id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstname VARCHAR(25), lastname VARCHAR(25), email VARCHAR(50), UNIQUE KEY(email), password VARCHAR(50));


def self.create_new(params)
    begin
      customer = Customer.create!(:firstname=>params[:firstname], :lastname => params[:lastname], :email => params[:email], :password => params[:password])
      return {:success => true, :message => "success", :id => customer.id }
    rescue => e
      return {:success => false, :message => e.message}
    end
  end

Should I add a uniqueness validation at model level to implement this?

0

1 Answer 1

2

You have added db backed validation, which is working. Now you should add explicit validation in your model (as you've suggested), so that it throws an exception saying what is wrong.

So adding validates :email, uniqueness: true to the model would do what you expect.

Sign up to request clarification or add additional context in comments.

3 Comments

you could use it for sure, but according to rails styles guide, it is more conventional to write as I've shown: (github.com/bbatsov/rails-style-guide)
@AndreyDeineko i guess validates :email, presence: true will just check for the presence of email and what the question is asking for the validation of uniqueness[ not presence ]. am i missing something? i guess not.
ooo, sure-sure, it should beuniqueness, just a typo :) let me edit the answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.