【问题标题】:Rails ActiveRecord Migration not creating some columns after successful migration成功迁移后 Rails ActiveRecord 迁移未创建某些列
【发布时间】:2016-11-18 04:08:27
【问题描述】:

我正在从一场比赛中创建一个新模型,其中包含一个主队和一个客队。 如果我运行 rake db:reset,它运行没有错误,但前三个字段(home_team、away_team 和 League)没有在数据库中生成,其他字段都可以。 这是我的迁移:

    class CreateGames < ActiveRecord::Migration[5.0]
      def change
       create_table :games do |t|
         t.references :home_team, references: :teams, foreign_key: true, index: true
         t.references :away_team, references: :teams, foreign_key: true, index: true
         t.belongs_to :league, foreign_key: true
         t.integer :round
         t.datetime :date

         t.timestamps
       end
     end
   end

这是生成的 schema.rb

      create_table "games", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
        t.integer  "round"
        t.datetime "date"
        t.datetime "created_at", null: false
        t.datetime "updated_at", null: false
      end

但是,对我来说最奇怪的是我有另一个事务迁移,这很好用:

    class CreateTransactions < ActiveRecord::Migration[5.0]
      def change
        create_table :transactions do |t|
          t.references :from_user, references: :users, foreign_key: true, index: true
          t.references :to_user, references: :users, foreign_key: true, index: true
          t.decimal :amount        

          t.timestamps
        end
      end
    end

【问题讨论】:

  • 你应该用过rake db:migrate
  • 可能表 teams 不存在。尽量避免使用references,而是使用t.integer
  • 查看add_reference 的文档,我觉得references 并不关心references: :teams 选项。您能否指出我正在关注的文档?

标签: ruby-on-rails ruby activerecord ruby-on-rails-5 rails-migrations


【解决方案1】:

rake db:reset 不会为您运行最新的迁移。它将运行db:dropdb:setupdb:setup 本身然后运行 ​​db:schema:loaddb:seed

所以在运行db:reset 时,它会删除数据库,从您的模式中再次创建它,并使用种子数据初始化数据库。它不会运行任何挂起的迁移。

在执行db:reset 之后,您需要运行db:migrate 以应用挂起的迁移。成功的迁移将为您更新架构,以便在您下次运行 db:setupdb:reset 时自动应用这些迁移。

如果您之前运行过db:migrate,它们可能会失败,并使您的 schema.rb 处于“损坏”状态。您可能想尝试将架构回滚到以前的版本并重新运行迁移以确保您没有收到任何错误。

注意,这不是一个解决方案,而是一个冗长的评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-16
    • 1970-01-01
    • 2021-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    相关资源
    最近更新 更多