How to make a unique column in rails active records other than id

class CreateUsers < ActiveRecord::Migration
   def up
     create_table :users do |t|
        t.string "email", :unique=>true

      

I tried to add this unique setting to make this unique email id unique in the rails model but its not working, so how can I make this unique email id unique?

+3


source to share


2 answers


The option unique

should be passed to the call add_index

, not where you define your column.

Update the migration definition as follows:



class CreateUsers < ActiveRecord::Migration
   def up
     create_table :users do |t|
        t.string "email"
     end
     add_index :users, :email, unique: true
   end
   ...
end

      

And if you don't want to allow null then use t.string :email, null: false

.

+13


source


Why put constraints on the db level, I think model-level validation is more than enough, and at least when you need to change or remove constraints, you won't find that you need to add a new migration



class User < ActiveRecord::Base
  validates :email, uniqueness: true
end

      

+3


source







All Articles