Duplicate column name error when running migration

左心房为你撑大大i 提交于 2019-12-09 12:26:30

问题


Whenever I run a migration in my Rails app, I get an error from SQLite3:

SQLite3::SQLException: duplicate column name: photo_file_name: ALTER TABLE "users" ADD "photo_file_name" varchar(255)

I already have a "Add Photo to User" migration. Here it is:

class AddAttachmentPhotoToUsers < ActiveRecord::Migration
   def self.up
     change_table :users do |t|
     t.has_attached_file :photo
    end
   end

  def self.down
   drop_attached_file :users, :photo
  end
end

And here is the user migration:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
    t.string :name
    t.string :title
    t.string :department
    t.text :skills
    t.boolean :available

    t.timestamps
   end
 end
end

I'm a bit confused by it because it's telling me there is a duplicate column name "photo_file_name" but that I need to add it to the Users table? That doesn't make sense. Shouldn't I need to remove it?

Let me know if you need any other details about my app.


回答1:


That happens if you migrations are not in sync with the database schema. This could happen if

  • you modified the database schema "by hand"
  • you changed a migration file being run
  • migrations have not been updated in the schema_migrations table

If you are not relying on the data in the database, a rake db:reset would re-run all migrations from scratch. Otherwise you have to make the conflicting migration recognized as already-run by adding to the schema_migrations table.

See RailsGuides of migrations as well.




回答2:


I've also solved this problem by logging into the heroku database, and then dropping only the offending column. I think this is a less-destructive solution.




回答3:


  • drop the development schema from your workbench
  • run rails db:create db:migrate


来源:https://stackoverflow.com/questions/13333580/duplicate-column-name-error-when-running-migration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!