Adrien Cadet
Adrien Cadet

Reputation: 1341

Uninitialized constant #{MIGRATION_NAME}::#{TABLE_NAME} when running migration

I have a Rails migration that creates some entries into my table. This table has been created in previous migration. Then, table is existing, for sure.

However, when I am running it, I get this error:

uninitialized constant AddInitialStates::State

Here is a sample of my migration:

class AddInitialStates < ActiveRecord::Migration
  def up
    State.create :short_name => 'AL', :long_name => 'Alabama'
    State.create :short_name => 'AK', :long_name => 'Alaska'

    # ... other create requests
  end
end

Upvotes: 2

Views: 945

Answers (1)

Adrien Cadet
Adrien Cadet

Reputation: 1341

Solution is quite simple actually. When running rake db:migrate, migration tool expects models to exist. Therefore, here, we get a uninitialized constant error. Migration tool is searching a State model and will use it to call create method.

Then, there are several ways to fix this issue. Most simple is to create missing models.

Otherwise, if you do not want to create them, here is a simple fix. You might need it if you are running transitional migrations to end in right schema version.

For each faulty migration, insert this code within it:

class MyMigration < ActiveRecord::Migration
  def MyTable < ActiveRecord::Base; end

  def change
    # Your migration
  end
end

These solutions work for every similar solution where a model/entity/table is not found by Rake.

By the way, you should avoid these create requests. Use seeds.rb file instead.

Upvotes: 1

Related Questions