db:migrate unknown attribute on insert via migration

I’m running Rails 5.0.6, and I can’t Google myself to any other occurences of this problem.

The migrations fail when I have a migration that inserts data into a table, that has data for a column that was added in a previous migration file executed by the same migrate command

Basically I have 3 migrations that are run with the following command
rails db:migrate

``

first migration chronologically:

create_table :campaign_orders do |t|
t.integer :order
end

``

second migration:

add_column :campaign_orders, :priority, :integer

``

third migration:

CampaignOrder.create(order: 0, priority: 1)

``

The third migration fails, if all migrations are outstanding when running migrate command, but succeeds if you run the migrate command again. It fails with the following error:

rails aborted!
StandardError: An error has occurred, all later migrations canceled:
unknown attribute ‘priority’ for CampaignOrder.
/Users/tomwilliams/Projects/incard-rails/db/migrate/20190326143614_insert_accepted_email_campaign.rb:66:in up' /Users/tomwilliams/Projects/incard-rails/bin/rails:9:in require’
/Users/tomwilliams/Projects/incard-rails/bin/rails:9:in <top (required)>' /Users/tomwilliams/Projects/incard-rails/bin/spring:15:in <top (required)>’
bin/rails:3:in load' bin/rails:3:in
Caused by:
ActiveModel::UnknownAttributeError: unknown attribute ‘priority’ for CampaignOrder.
/Users/tomwilliams/Projects/incard-rails/db/migrate/20190326143614_insert_accepted_email_campaign.rb:66:in up' /Users/tomwilliams/Projects/incard-rails/bin/rails:9:in require’
/Users/tomwilliams/Projects/incard-rails/bin/rails:9:in <top (required)>' /Users/tomwilliams/Projects/incard-rails/bin/spring:15:in <top (required)>’
bin/rails:3:in load' bin/rails:3:in
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

Now, I can just “fix” it by running the migrate command again, or as I did, rollback the migrations and put the added column in the create table migration and deleting the add_column migration.

My question is - does anybody know if this is a known issue, and if so, could someone provide a link.

You need to call .reset_column_information in third migration. Please refer
https://api.rubyonrails.org/classes/ActiveRecord/ModelSchema/ClassMethods.html#method-i-reset_column_information for details.

You can insert and update data in migration, but you might want to consider using db/seeds.rb instead.
https://guides.rubyonrails.org/active_record_migrations.html#migrations-and-seed-data

HTH

Thanks for the links - that clears it up.

The reason for using a migration and not seed data, is that this is real data needed in our production db, and I use seeds.rb to populate my development db with data to test with.

onsdag den 27. marts 2019 kl. 22.33.42 UTC+1 skrev Eito Katagiri: