Gustavo Canedo
Gustavo Canedo

Reputation: 11

Rails ActiveRecord Migration not creating some columns after successful migration

I'm creating a new model from a game, with a home team and a away team. If i run a rake db:reset, it runs without errors, but the first three fields (home_team, away_team and league) aren't generated in the database, the other fields are ok. This is my migrate:

    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

Here's is the schema.rb generated

      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

But, the most weird for me is that i have another migration for Transactions, and this works fine:

    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

Upvotes: 1

Views: 1236

Answers (1)

David
David

Reputation: 3610

rake db:reset will not run the latest migrations for you. It will run db:drop and db:setup. db:setup itself then runs db:schema:load and db:seed.

So in running db:reset, it drops the database, creates it again from your schema, and initialises the database with the seed data. It does NOT run any pending migrations.

After doing db:reset you will then need to run db:migrate to apply the pending migrations. The successfull migrations will update the schema for you so that next time you run db:setup or db:reset those migrations will automatically be applied.

If you had previously run db:migrate they may have failed and left your schema.rb in a 'corrupt' state. You may want to try to rollback your schema to a prior version and rerun the migrations to ensure you aren't getting any errors.

Note, this is not so much a solution, but a lengthy comment.

Upvotes: 2

Related Questions