0

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

Brad Cypert
  • 671
  • 1
  • 8
  • 29

2 Answers2

1

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

Leantraxxx
  • 4,506
  • 3
  • 38
  • 56
  • Oh awesome! I guess I was confused if I needed to do a db:migrate afterwards. I'm still learning about rake :3 Thanks so much for your help, your answer was extremely informative! – Brad Cypert Feb 28 '14 at 21:03
0

Just adding validation in the model is useless if you are ever planning to use insert_all, upsert_all, etc on that table