Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rake Aborted , on add_index(:users, :email, {:unique=>true})

I am currently working on ruby on rails 3 tutorial by michael hartl. I am running into this problem when I try to call db:migrate. Could someone help me figure out why its aborting. Thanks!

** Invoke db:migrate (first_time) ** Invoke environment (first_time) ** Execute environment ** Invoke db:load_config (first_time) ** Execute db:load_config ** Execute db:migrate == AddEmailUniquenessIndex: migrating ======================================== -- add_index(:users, :email, {:unique=>true}) rake aborted! An error has occurred, this and all later migrations canceled: SQLite3::ConstraintException: indexed columns are not unique: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")

CODE

class AddEmailUniquenessIndex < ActiveRecord::Migration
  def up
    add_index :users, :email, :unique => true
  end

  def down
    remove_index :users, :email
  end
end

USER CODE

# == Schema Information
#
# Table name: users
#
#  id         :integer          not null, primary key
#  name       :string(255)
#  email      :string(255)
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class User < ActiveRecord::Base
  attr_accessor :password
  attr_accessible :email, :name, :password, :password_confirmation

  email_regex = /\A[\W+\-.]+@[a-z\d\-.]+\.|[a-z]+\z/i

  validates :name, :presence => true,
                   :length => { :maximum => 50 }
  validates :email, :presence => true,
                    :format => { :with => email_regex },
                    :uniqueness => { :case_sensitive => false }
  validates :password, :presence => true,
                       :confirmation => true,
                       :length => { :within => 6..40 }


end
like image 340
AustinT Avatar asked Dec 06 '25 17:12

AustinT


1 Answers

Nothing wrong with your migration. The error simply means you have existing email duplicates data in db.

Check your users table, set unique emails for existing rows or delete these rows. Then run the migration again.

Update: Please note that even if you remove the unique constraint from migration and add validates_uniqueness_of :email to your Active Model, the problem would still eat you in the future.

The root problem is your data is in a 'bad' state. If you have two rows having the same email address (or it's also possible they both have blank email), after adding validates_uniqueness_of :email your User model instance for these two rows won't be valid. So it's still a data problem you have to fix.

like image 193
James Chen Avatar answered Dec 08 '25 08:12

James Chen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!