【问题标题】:Why do I keep getting this error when I try and run rake db:migrate?为什么我在尝试运行 rake db:migrate 时不断收到此错误?
【发布时间】:2012-05-16 14:37:40
【问题描述】:
==  AddAncestryToMessages: migrating ==========================================
-- add_column(:messages, :ancestry, :string)
rake aborted!
An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: no such table: messages: ALTER TABLE "messages" ADD "ancestry" varchar(255)

所以我的应用程序有你可以发布的消息(有点像 twitter)并且我添加了回复,我正在使用祖先 gem 来做到这一点。

我在schema.rb 文件中的代码(我认为这是每次运行 rake db:migrate 时它用来创建表的文件。但我可能错了(这可能是问题所在!)

  create_table "messages", :force => true do |t|
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at", :null => false
    t.datetime "updated_at", :null => false
    t.string   "ancestry"
  end

  add_index "messages", ["user_id", "created_at", "ancestry"], :name =>   "index_messages_on_user_id_and_created_at_and_ancestry"

【问题讨论】:

    标签: ruby-on-rails migration dbmigrate ancestry


    【解决方案1】:

    哦,现在我明白了:您已将代码添加到 schema.rb,但您必须使用迁移。从schema.rb 中删除您手动添加的代码并运行:

    rails g migration CreateMessages
    

    您将获得文件 db/migrate/[timestamp]_create_messages.rb。用您的代码填充其change 方法,然后运行(它应该为您创建,但为空。对于旧版本,它被命名为up):

    rake db:migrate
    

    此命令将自行更改您的schema.rb不要手动更改它!(至少在您成为成熟的 Rails 程序员之前)。

    【讨论】:

    • 嗯,这对我不起作用。我从 add_index 方法中取出了 t.string "ancestry" 和 "ancestry",因此将其更改回原来的状态。然后我运行 rails g migration CreateMessages 它为我创建了 rb 文件。然后我将上面的所有代码复制并粘贴到 up 中。这一切都正确吗?
    • 等一下。 把它改回原来的状态 -- 你是什么意思?您已经有表并且只想为其添加索引?如果您只需要向您拥有的表添加索引,那么您的up/change 方法应该只包含add_index ....。此外,如果您有up 方法,则使用remove_index, :name => "..." 填充down 方法。
    • @user1123905,几乎正确。在新 rb 文件的 up 中,您应该调用 add_column 和 add_index,因为正如 jdoe 所指出的,您已经拥有该表。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-21
    • 1970-01-01
    • 2022-06-13
    • 1970-01-01
    • 2020-05-21
    • 1970-01-01
    相关资源
    最近更新 更多