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

我目前正在研究michael hartl的ruby on rails 3教程。 当我尝试调用db:migrate时,我遇到了这个问题。 有人可以帮我弄清楚为什么会流产。 谢谢!

** 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")

 class AddEmailUniquenessIndex  true end def down remove_index :users, :email end end 

用户代码

 # == 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  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 

您的迁移没有错。 该错误仅表示您在db中具有现有的电子邮件重复数据。

检查您的用户表,为现有行设置唯一的电子邮件或删除这些行。 然后再次运行迁移。

更新:请注意,即使您从迁移中删除了唯一约束并将validates_uniqueness_of :email添加到您的活动模型,该问题仍将在您将来使用。

根本问题是您的数据处于“不良”状态。 如果您有两行具有相同的电子邮件地址(或者它们也可能都有空白电子邮件),则在添加validates_uniqueness_of :email您的这两行的User模型实例将无效。 所以它仍然是你必须解决的数据问题。