Question

So I've created a model named User and email has been required on it, but I'd like to make that unique before I potentially deploy my app. I'm extremely new to rails but I've looked around for this scenario and I've only found things that allow you to add NEW columns and specify them as unique.

Any help is appreciated. I'm not sure if I should be doing this from the rails console or by adding validates_uniqueness_of :email to my Model or what exactly. I've tried that and ran rake db:migrate and nothing has happened.

Thanks in advance!

A Python Guy :P

Was it helpful?

Solution

As you said, you can make a field unique adding uniqueness validation You don't need to run migrations. (Im supposing that you ran migrations in order to create the User model/table with email field before)

You need to add this on your model

class User < ActiveRecord::Base
  validates :email, uniqueness: true # :email makes reference to the user's email attribute
end

To test this. Open you console. (rails c on terminal) Then you can create a user:

User.create! email: "some@mail.com" 

Then, do this for second time:

User.create! email: "some@mail.com"

You will see a validation error

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

If you execute create instead create! you won't see the Exception. Be careful with that

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top