Rails aborted standarderror an error has occurred this and all later migrations canceled

I started to have a issue with migrations with the project I was working on. I've started a brand new one but the issue is still appearing the same. Error messages appearing on attempts to do r...

I started to have a issue with migrations with the project I was working on. I’ve started a brand new one but the issue is still appearing the same. Error messages appearing on attempts to do rake db:migrate
(have tried both starting new project with the default database- sqlite3 and the optional- postgresql ), however, after generating a model (tried both with rails g scaffold Schedule name:name dep_date:datetime and just model — rails g model Schedule name:name dep_date:datetime ) migration stays down.

the migration itself is:

class CreateSchedules < ActiveRecord::Migration[5.0]
def change
create_table :schedules do |t|
t.name :name
t.datetime :dep_date

end
end

command : rake db:migrate:status
give:

database: travel_t_challenge_development

Status Migration ID Migration Name

down 20160809121048 Create schedules

commands:

rake db:migrate
rake RAILS_ENV=production db:migrate or
rake db:migrate:up VERSION=20160809121048 or
bundle exec rake db:migrate VERSION=20160809121048
(or redo)
result in the same error:

== 20160809121048 CreateSchedules: migrating ==================================
— create_table(:schedules)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

wrong number of arguments (1 for 0)
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:4:in block in change' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/schema_statements.rb:277:increate_table’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:845:in block in method_missing' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:inblock in say_with_time’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:in say_with_time' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:834:inmethod_missing’
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:3:in change' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:788:inexec_migration’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:772:in block (2 levels) in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:771:inblock in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in with_connection' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:770:inmigrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:950:in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1211:inblock in execute_migration_in_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:in block in ddl_transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:inblock in transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/transaction.rb:189:in within_new_transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:intransaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/transactions.rb:211:in transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:inddl_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1210:in execute_migration_in_transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1183:inblock in migrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:in each' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:inmigrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in block in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1298:inwith_advisory_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1005:inup’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:989:in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:161:inmigrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:58:in block (2 levels) in <top (required)>' /Users/[username]/.rvm/gems/ruby-2.2.2/gems/rake-11.2.2/exe/rake:27:in<top (required)>’
/Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in eval' /Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in


ArgumentError: wrong number of arguments (1 for 0)
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:4:in block in change' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/schema_statements.rb:277:increate_table’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:845:in block in method_missing' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:inblock in say_with_time’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:in say_with_time' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:834:inmethod_missing’
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:3:in change' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:788:inexec_migration’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:772:in block (2 levels) in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:771:inblock in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in with_connection' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:770:inmigrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:950:in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1211:inblock in execute_migration_in_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:in block in ddl_transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:inblock in transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/transaction.rb:189:in within_new_transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:intransaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/transactions.rb:211:in transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:inddl_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1210:in execute_migration_in_transaction' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1183:inblock in migrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:in each' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:inmigrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in block in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1298:inwith_advisory_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1005:inup’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:989:in migrate' /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:161:inmigrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:58:in block (2 levels) in <top (required)>' /Users/[username]/.rvm/gems/ruby-2.2.2/gems/rake-11.2.2/exe/rake:27:in<top (required)>’
/Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in eval' /Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in
Tasks: TOP => db:migrate
(See full trace by running task with —trace)

Dropping and setting up/creating the database again hasn’t helped either.

System configuration

Rails version:5.0.0
Ruby version:2.2.3

Содержание

  1. Tips for Fixing Ruby Migration Errors
  2. Solution #1:
  3. Solution #2 (not preferred):
  4. rake db:migrate doesn’t work (rake aborted! StandardError: An error has occurred) #26091
  5. Comments
  6. System configuration

Tips for Fixing Ruby Migration Errors

When you are moving quickly, sometimes the migrations in your locally running app get tripped up. This may be due to something on your side or coordinating with your team. There are a number of possible not-fun reasons. Whatever the cause, you just want to get past it and continue writing code.

Here are some things I have learned to resolve Ruby migration errors involving duplicate columns.

You might get a message like this when you run your migration. The PG refers to the PostgreSQL database I’m using, but this can happen regardless of your database choic

The problem here is that your migration will not run because those changes already exist in your schema, so you are stuck in a loop. You have to run the migration to be able to render your code locally, but you can’t run the migration because your app sees that those elements already exist.

Solution #1:

Comment out the offending part of the migrations and rerun, then uncomment them.

If you are sure your schema is correct (or if you have just manually copied it over from the source file in your GitHub repo), you can comment out the part of the migration files that are getting stuck, run your migration, then uncomment that code.

You need to include the top and bottom part of the migration file. Just comment out the middle, like this:

Then, rerun the migration.

Then, you will see something like this:

The migrations actually run, but without the offending pieces. Your app should now render locally.

Remember that you now need to uncomment the parts of those migrations, and then add and commit them back.

Solution #2 (not preferred):

Delete the offending migration files completely, confirm your schema is correct (or add in your correct schema manually from the GitHub source), run the migrations, then add your migrations back manually, exactly as they appeared before, in the same order.

If the first solution does not work for you, try this surgical approach. It is not recommended, because there are many ways to screw it up. But if you are desperate, here are the steps .

First, manually delete the offending migrations from your local app version.

Then, rerun the migration.

Your app should now render locally.

But remember you need those migrations back in there!

So next, put the migrations back exactly as they were before.

Do this manually. Get the original migration files from your source repo in GitHub. You need to make sure they stay in the exact original order, since the order in the app is the order in which they are processed when you run a migration.

Note: When I do this, GitHub displays the migrations in the reverse chronological order from the order in my local app. This requires manually transposing the order to figure out where yours should be put back into your local version. (I use RubyMine; your IDE may display them differently.)

Now you wil be able to work on code and push your commits up safely so it will not impact your team. Good luck!

Источник

rake db:migrate doesn’t work (rake aborted! StandardError: An error has occurred) #26091

I started to have a issue with migrations with the project I was working on. I’ve started a brand new one but the issue is still appearing the same. Error messages appearing on attempts to do rake db:migrate
(have tried both starting new project with the default database- sqlite3 and the optional- postgresql ), however, after generating a model (tried both with rails g scaffold Schedule name:name dep_date:datetime and just model — rails g model Schedule name:name dep_date:datetime ) migration stays down.

the migration itself is:

class CreateSchedules block in change’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/schema_statements.rb:277:in create_table’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:845:in block in method_missing’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:in block in say_with_time’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:in say_with_time’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:834:in method_missing’
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:3:in change’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:788:in exec_migration’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:772:in block (2 levels) in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:771:in block in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in with_connection’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:770:in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:950:in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1211:in block in execute_migration_in_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:in block in ddl_transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in block in transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/transaction.rb:189:in within_new_transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/transactions.rb:211:in transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:in ddl_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1210:in execute_migration_in_transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1183:in block in migrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:in each’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:in migrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in block in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1298:in with_advisory_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1005:in up’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:989:in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:161:in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:58:in block (2 levels) in ‘ /Users/[username]/.rvm/gems/ruby-2.2.2/gems/rake-11.2.2/exe/rake:27:in ‘
/Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in eval’ /Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in


ArgumentError: wrong number of arguments (1 for 0)
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:4:in block in change’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/schema_statements.rb:277:in create_table’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:845:in block in method_missing’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:in block in say_with_time’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:814:in say_with_time’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:834:in method_missing’
/Users/[username]/workspace/travel_t_challenge/db/migrate/20160809121048_create_schedules.rb:3:in change’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:788:in exec_migration’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:772:in block (2 levels) in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:771:in block in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/connection_pool.rb:398:in with_connection’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:770:in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:950:in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1211:in block in execute_migration_in_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:in block in ddl_transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in block in transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/transaction.rb:189:in within_new_transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/connection_adapters/abstract/database_statements.rb:232:in transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/transactions.rb:211:in transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1279:in ddl_transaction’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1210:in execute_migration_in_transaction’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1183:in block in migrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:in each’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1182:in migrate_without_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in block in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1298:in with_advisory_lock’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1131:in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:1005:in up’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/migration.rb:989:in migrate’ /Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/tasks/database_tasks.rb:161:in migrate’
/Users/[username]/.rvm/gems/ruby-2.2.2@global/gems/activerecord-5.0.0/lib/active_record/railties/databases.rake:58:in block (2 levels) in ‘ /Users/[username]/.rvm/gems/ruby-2.2.2/gems/rake-11.2.2/exe/rake:27:in ‘
/Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in eval’ /Users/[username]/.rvm/gems/ruby-2.2.2/bin/ruby_executable_hooks:15:in ‘
Tasks: TOP => db:migrate
(See full trace by running task with —trace)

Dropping and setting up/creating the database again hasn’t helped either.

System configuration

Rails version:5.0.0
Ruby version:2.2.3

The text was updated successfully, but these errors were encountered:

Источник

Introduction

This will be a memo for learning.

This time, we will deal with the error that occurs after executing $ rails db: migrate or $ rails db: migrate.

== 20200107095832 CreateMicroposts: migrating =================================
-- create_table(:microposts)
rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::SQLException: table "microposts" already exists: CREATE TABLE "microposts" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "content" text, "user_id" integer, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)

Continued below

Cause

I think there is something wrong with the migration of the command I did last time. Probably an error occurred in the middle of the migration process and the table was generated, but the migration that generated the table remains unexecuted. Is it in such a state? I think

solution

$ rails db:migrate:reset

After resetting the database

$ rails db:migrate

Migrate again

This command is used when you want to delete the database, modify the new migration file, and perform migration again.

$ rails db:migrate:reset

An error occurs after resetting the database!

ActiveRecord::NoEnvironmentInSchemaError: 

Environment data not found in the schema. To resolve this issue, run: 

        bin/rails db:environment:set RAILS_ENV=development


Tasks: TOP => db:migrate:reset => db:drop => db:check_protected_environments
(See full trace by running task with --trace)

Coping

rake db:migrate:status

Check the status of db with the above command.
⬇︎ Execution content

 up     20201013130002  Devise create users
 down    20201015132219  Add devise to users

Apparently, the migration file at the bottom is suspicious. .. ..
I checked the editor
I created the same migration file twice. ..
So, let’s delete the migration file at the bottom.

  • If it is down, there is no problem even if you delete the file manually.
$ rm -rf db/migrate/20201015132219_add_devise_to_users.rb

This will migrate again.
⬇︎ Execution result

== 20201013130002 DeviseCreateUsers: migrating ================================
-- create_table(:users)
   -> 0.0061s
-- add_index(:users, :email, {:unique=>true})
   -> 0.0014s
-- add_index(:users, :reset_password_token, {:unique=>true})
   -> 0.0011s
== 20201013130002 DeviseCreateUsers: migrated (0.0087s) =======================

I was able to do it without any problems!

Finally

This time I learned about errors when migrating.
DB reset did not solve the problem.
The cause was a duplicate migration file.

I would appreciate it if you could point out any mistakes.

When you are moving quickly, sometimes the migrations in your locally running app get tripped up. This may be due to something on your side or coordinating with your team. There are a number of possible not-fun reasons. Whatever the cause, you just want to get past it and continue writing code.

Here are some things I have learned to resolve Ruby migration errors involving duplicate columns.

Problem: Duplicate column error

You might get a message like this when you run your migration. The PG refers to the PostgreSQL database I’m using, but this can happen regardless of your database choic

rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

PG::DuplicateColumn: ERROR:  column "stocksplitratio" of relation "tags" already exists

The problem here is that your migration will not run because those changes already exist in your schema, so you are stuck in a loop. You have to run the migration to be able to render your code locally, but you can’t run the migration because your app sees that those elements already exist.

Solution #1:

Comment out the offending part of the migrations and rerun, then uncomment them.

If you are sure your schema is correct (or if you have just manually copied it over from the source file in your GitHub repo), you can comment out the part of the migration files that are getting stuck, run your migration, then uncomment that code.

You need to include the top and bottom part of the migration file. Just comment out the middle, like this:

class AddMoreExpandedEntityFieldsToTags < ActiveRecord::Migration
def change
  change_table :tags do |t|
    # t.string :filingtype
    # t.string :quarter
    ... all your info here
    # t.string :accountingchangetype
  end
end
end

Then, rerun the migration.

rake db:migrate

Then, you will see something like this:

Changes to be committed:
 (use "git reset HEAD ..." to unstage)

       new file:   db/migrate/20160526221804_add_more_expanded_entity_fields_to_tags.rb
       new file:   db/migrate/20160530151904_add_stock_split_ratio_tag_info.rb

Changes not staged for commit:
 (use "git add ..." to update what will be committed)
 (use "git checkout -- ..." to discard changes in working directory)

       modified:   db/migrate/20160526221804_add_more_expanded_entity_fields_to_tags.rb
       modified:   db/migrate/20160530151904_add_stock_split_ratio_tag_info.rb

The migrations actually run, but without the offending pieces. Your app should now render locally.

Remember that you now need to uncomment the parts of those migrations, and then add and commit them back.

Solution #2 (not preferred):

Delete the offending migration files completely, confirm your schema is correct (or add in your correct schema manually from the GitHub source), run the migrations, then add your migrations back manually, exactly as they appeared before, in the same order.

If the first solution does not work for you, try this surgical approach. It is not recommended, because there are many ways to screw it up. But if you are desperate, here are the steps …

First, manually delete the offending migrations from your local app version.

Then, rerun the migration.

Your app should now render locally.

But remember you need those migrations back in there!

So next, put the migrations back exactly as they were before.

Do this manually. Get the original migration files from your source repo in GitHub. You need to make sure they stay in the exact original order, since the order in the app is the order in which they are processed when you run a migration.

Note: When I do this, GitHub displays the migrations in the reverse chronological order from the order in my local app. This requires manually transposing the order to figure out where yours should be put back into your local version. (I use RubyMine; your IDE may display them differently.)

Now you wil be able to work on code and push your commits up safely so it will not impact your team. Good luck!

Skip to content



Open


Issue created Dec 03, 2020 by Marc Peiser@marcpeiser

Database migration errors after an upgrade

Summary

I’ve had a report that some users are getting error 500 when trying to login to Gitlab after a recent upgrade. I am able to login with no issues. I then tried to impersonated the user who reported the issue and also got an error 500.

Steps to reproduce

Upgrade gitlab-ce:amd64 on Ubuntu 18.04 from version 13.5.1-ce.0 to 13.6.1-ce.0 using apt upgrade.

What is the current bug behavior?

Error 500 page is displayed when some users try login. When I try run a gitlab-ctl reconfigure, I get some database migration errors, see below.

What is the expected correct behavior?

We expect to see the GitLab home page and not this 500 error page.

Relevant logs

Relevant logs — Errors from gitlab-ctl reconfigure

Recipe: gitlab::database_migrations

  • bash[migrate gitlab-rails database] action run
    [execute] rake aborted!
    StandardError: An error has occurred, all later migrations canceled:

          PG::UndefinedObject: ERROR:  operator class "gin_trgm_ops" does not exist for access method "gin"
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in `block in add_concurrent_index'
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in `disable_statement_timeout'
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in `add_concurrent_index'
          /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in `up'
          /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in `block (3 levels) in <top (required)>'
          /opt/gitlab/embedded/bin/bundle:23:in `load'
          /opt/gitlab/embedded/bin/bundle:23:in `<main>'
    
          Caused by:
          ActiveRecord::StatementInvalid: PG::UndefinedObject: ERROR:  operator class "gin_trgm_ops" does not exist for access method "gin"
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in `block in add_concurrent_index'
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in `disable_statement_timeout'
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in `add_concurrent_index'
          /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in `up'
          /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in `block (3 levels) in <top (required)>'
          /opt/gitlab/embedded/bin/bundle:23:in `load'
          /opt/gitlab/embedded/bin/bundle:23:in `<main>'
    
          Caused by:
          PG::UndefinedObject: ERROR:  operator class "gin_trgm_ops" does not exist for access method "gin"
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in `block in add_concurrent_index'
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in `disable_statement_timeout'
          /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in `add_concurrent_index'
          /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in `up'
          /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in `block (3 levels) in <top (required)>'
          /opt/gitlab/embedded/bin/bundle:23:in `load'
          /opt/gitlab/embedded/bin/bundle:23:in `<main>'
          Tasks: TOP => db:migrate
          (See full trace by running task with --trace)
          == 20201021101956 AddIndexRouteOnNameTrigramToRoute: migrating ================
          -- transaction_open?()
             -> 0.0000s
          -- index_exists?(:routes, :name, {:name=>"index_route_on_name_trigram", :using=>:gin, :opclass=>{:name=>:gin_trgm_ops}, :algorithm=>:concurrently})
             -> 0.0071s
          -- add_index(:routes, :name, {:name=>"index_route_on_name_trigram", :using=>:gin, :opclass=>{:name=>:gin_trgm_ops}, :algorithm=>:concurrently})

    ================================================================================
    Error executing action run on resource ‘bash[migrate gitlab-rails database]’

    Mixlib::ShellOut::ShellCommandFailed

    Expected process to exit with [0], but received ‘1’
    —- Begin output of «bash» «/tmp/chef-script20201203-17121-1c01fad» —-
    STDOUT: rake aborted!
    StandardError: An error has occurred, all later migrations canceled:

    PG::UndefinedObject: ERROR: operator class «gin_trgm_ops» does not exist for access method «gin»
    /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in block in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in disable_statement_timeout’
    /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in up’
    /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in block (3 levels) in <top (required)>' /opt/gitlab/embedded/bin/bundle:23:in load’
    /opt/gitlab/embedded/bin/bundle:23:in `’

    Caused by:
    ActiveRecord::StatementInvalid: PG::UndefinedObject: ERROR: operator class «gin_trgm_ops» does not exist for access method «gin»
    /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in block in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in disable_statement_timeout’
    /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in up’
    /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in block (3 levels) in <top (required)>' /opt/gitlab/embedded/bin/bundle:23:in load’
    /opt/gitlab/embedded/bin/bundle:23:in `’

    Caused by:
    PG::UndefinedObject: ERROR: operator class «gin_trgm_ops» does not exist for access method «gin»
    /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in block in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in disable_statement_timeout’
    /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in up’
    /opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in block (3 levels) in <top (required)>' /opt/gitlab/embedded/bin/bundle:23:in load’
    /opt/gitlab/embedded/bin/bundle:23:in `’
    Tasks: TOP => db:migrate
    (See full trace by running task with —trace)
    == 20201021101956 AddIndexRouteOnNameTrigramToRoute: migrating ================
    — transaction_open?()
    -> 0.0000s
    — index_exists?(:routes, :name, {:name=>»index_route_on_name_trigram», :using=>:gin, :opclass=>{:name=>:gin_trgm_ops}, :algorithm=>:concurrently})
    -> 0.0071s
    — add_index(:routes, :name, {:name=>»index_route_on_name_trigram», :using=>:gin, :opclass=>{:name=>:gin_trgm_ops}, :algorithm=>:concurrently})
    STDERR:
    —- End output of «bash» «/tmp/chef-script20201203-17121-1c01fad» —-
    Ran «bash» «/tmp/chef-script20201203-17121-1c01fad» returned 1

    Resource Declaration:

    In /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/database_migrations.rb

    55: bash «migrate gitlab-rails database» do
    56: code <<-EOH
    57: set -e
    58: log_file=»#{node[‘gitlab’][‘gitlab-rails’][‘log_directory’]}/gitlab-rails-db-migrate-$(date +%Y-%m-%d-%H-%M-%S).log»
    59: umask 077
    60: /opt/gitlab/bin/gitlab-rake gitlab:db:configure 2>& 1 | tee ${log_file}
    61: STATUS=${PIPESTATUS[0]}
    62: chown #{account_helper.gitlab_user}:#{account_helper.gitlab_group} ${log_file}
    63: echo $STATUS > #{db_migrate_status_file}
    64: exit $STATUS
    65: EOH
    66: environment env_variables unless env_variables.empty?
    67: notifies :run, «execute[clear the gitlab-rails cache]», :immediately
    68: dependent_services.each do |svc|
    69: notifies :restart, svc, :immediately
    70: end
    71: not_if «(test -f #{db_migrate_status_file}) && (cat #{db_migrate_status_file} | grep -Fx 0)»
    72: only_if { node[‘gitlab’][‘gitlab-rails’][‘auto_migrate’] }
    73: end

    Compiled Resource:

    Declared in /opt/gitlab/embedded/cookbooks/cache/cookbooks/gitlab/recipes/database_migrations.rb:55:in `from_file’

    bash(«migrate gitlab-rails database») do
    action [:run]
    default_guard_interpreter :default
    command nil
    backup 5
    interpreter «bash»
    declared_type :bash
    cookbook_name «gitlab»
    recipe_name «database_migrations»
    code » set -en log_file=»/var/log/gitlab/gitlab-rails/gitlab-rails-db-migrate-$(date +%Y-%m-%d-%H-%M-%S).log»n umask 077n /opt/gitlab/bin/gitlab-rake gitlab:db:configure 2>& 1 | tee ${log_file}n STATUS=${PIPESTATUS[0]}n chown git:git ${log_file}n echo $STATUS > /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-900d21efabf9c273ecb3fe002e5d0f25-1b6a590b197n exit $STATUSn»
    domain nil
    user nil
    not_if «(test -f /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-900d21efabf9c273ecb3fe002e5d0f25-1b6a590b197) && (cat /var/opt/gitlab/gitlab-rails/upgrade-status/db-migrate-900d21efabf9c273ecb3fe002e5d0f25-1b6a590b197 | grep -Fx 0)»
    only_if { #code block }
    end

    System Info:

    chef_version=15.14.0
    platform=ubuntu
    platform_version=18.04
    ruby=ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux]
    program_name=/opt/gitlab/embedded/bin/chef-client
    executable=/opt/gitlab/embedded/bin/chef-client

Running handlers:
There was an error running gitlab-ctl reconfigure:

bash[migrate gitlab-rails database] (gitlab::database_migrations line 55) had an error: Mixlib::ShellOut::ShellCommandFailed: Expected process to exit with [0], but received ‘1’
—- Begin output of «bash» «/tmp/chef-script20201203-17121-1c01fad» —-
STDOUT: rake aborted!
StandardError: An error has occurred, all later migrations canceled:

PG::UndefinedObject: ERROR: operator class «gin_trgm_ops» does not exist for access method «gin»
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in block in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in disable_statement_timeout’
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in up’
/opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in block (3 levels) in <top (required)>' /opt/gitlab/embedded/bin/bundle:23:in load’
/opt/gitlab/embedded/bin/bundle:23:in `’

Caused by:
ActiveRecord::StatementInvalid: PG::UndefinedObject: ERROR: operator class «gin_trgm_ops» does not exist for access method «gin»
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in block in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in disable_statement_timeout’
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in up’
/opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in block (3 levels) in <top (required)>' /opt/gitlab/embedded/bin/bundle:23:in load’
/opt/gitlab/embedded/bin/bundle:23:in `’

Caused by:
PG::UndefinedObject: ERROR: operator class «gin_trgm_ops» does not exist for access method «gin»
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:95:in block in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:276:in disable_statement_timeout’
/opt/gitlab/embedded/service/gitlab-rails/lib/gitlab/database/migration_helpers.rb:94:in add_concurrent_index' /opt/gitlab/embedded/service/gitlab-rails/db/migrate/20201021101956_add_index_route_on_name_trigram_to_route.rb:12:in up’
/opt/gitlab/embedded/service/gitlab-rails/lib/tasks/gitlab/db.rake:59:in block (3 levels) in <top (required)>' /opt/gitlab/embedded/bin/bundle:23:in load’
/opt/gitlab/embedded/bin/bundle:23:in `’
Tasks: TOP => db:migrate
(See full trace by running task with —trace)
== 20201021101956 AddIndexRouteOnNameTrigramToRoute: migrating ================
— transaction_open?()
-> 0.0000s
— index_exists?(:routes, :name, {:name=>»index_route_on_name_trigram», :using=>:gin, :opclass=>{:name=>:gin_trgm_ops}, :algorithm=>:concurrently})
-> 0.0071s
— add_index(:routes, :name, {:name=>»index_route_on_name_trigram», :using=>:gin, :opclass=>{:name=>:gin_trgm_ops}, :algorithm=>:concurrently})
STDERR:
—- End output of «bash» «/tmp/chef-script20201203-17121-1c01fad» —-
Ran «bash» «/tmp/chef-script20201203-17121-1c01fad» returned 1

Deprecations:

  • sidekiq_cluster[‘experimental_queue_selector’] has been deprecated since 13.6 and will be removed in 14.0. The experimental_queue_selector option is now called queue_selector.

Running handlers complete
Chef Infra Client failed. 1 resources updated in 22 seconds

Deprecations:

  • sidekiq_cluster[‘experimental_queue_selector’] has been deprecated since 13.6 and will be removed in 14.0. The experimental_queue_selector option is now called queue_selector.

Details of package version

Provide the package version installation details

Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-=======================================-========================-========================-==================================================================================== ii gitlab-ce 13.6.1-ce.0 amd64 GitLab Community Edition (including NGINX, Postgres, Redis) un gitlab-ee (no description available)

Environment details

  • Operating System: 18.04.5 LTS
  • Installation Target, remove incorrect values:
    • VM: AWS
  • Installation Type, remove incorrect values:
    • Upgrade from version 13.5.1
  • Is there any other software running on the machine: No
  • Is this a single or multiple node installation?
  • Resources
    • CPU: 4 core
    • Memory total: 16GB

Configuration details

Provide the relevant sections of `/etc/gitlab/gitlab.rb`

external_url 'https://gitlab.mydomain.com' nginx['redirect_http_to_https'] = true gitlab_rails['gitlab_email_from'] = 'myemail@mydomain.com' gitlab_rails['registry_path'] = "/data/registry" gitlab_rails['omniauth_enabled'] = true gitlab_rails['omniauth_allow_single_sign_on'] = ['saml'] gitlab_rails['omniauth_block_auto_created_users'] = false gitlab_rails['omniauth_auto_link_saml_user'] = true gitlab_rails['omniauth_providers'] = [ { name: 'saml', args: { assertion_consumer_service_url: 'https://gitlab.mydomain.com/users/auth/saml/callback', idp_cert_fingerprint: 'xxx', idp_sso_target_url: 'https://mytenant.okta.com/app/redacted_gitlab_1/xxx/sso/saml', issuer: 'https://gitlab.mydomain.com/', name_identifier_format: 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient' }, label: 'Okta' } ] gitlab_rails['backup_path'] = "/opt/backups" git_data_dirs({ "default" => { "path" => "/opt/git-data" } }) gitlab_rails['db_adapter'] = "postgresql" gitlab_rails['db_encoding'] = "utf8" gitlab_rails['db_database'] = "gitlab-db" gitlab_rails['db_username'] = "gitlab-user" gitlab_rails['db_password'] = "gitlab-password" gitlab_rails['db_host'] = "gitlab-host" gitlab_rails['db_port'] = 5432 gitlab_rails['smtp_enable'] = true gitlab_rails['smtp_address'] = "aaa" gitlab_rails['smtp_port'] = 25 gitlab_rails['smtp_authentication'] = false gitlab_rails['smtp_enable_starttls_auto'] = false gitlab_rails['smtp_tls'] = false postgresql['enable'] = false registry_nginx['ssl_certificate'] = "/etc/gitlab/ssl/gitlab.mydomain.com.crt" registry_nginx['ssl_certificate_key'] = "/etc/gitlab/ssl/gitlab.mydomain.com.key" registry['enable'] = true registry_external_url 'https://registry.mydomain.com' pages_external_url 'http://pages.mydomain.com' pages_nginx['enable'] = false

To give back to our community of developers, we looked at our database of thousands of projects and found the top 10 errors in Ruby on Rails projects. We’re going to show you what causes them and how to prevent them from happening. If you avoid these «gotchas,» it’ll make you a better developer.

Because data is king, we collected, analyzed, and ranked the top 10 Ruby errors from Ruby on Rails applications. Rollbar collects all the errors for each project and summarizes how many times each one occurred. We do this by grouping errors according to fingerprinting. Basically, we group two errors if the second one is just a repeat of the first. This gives users a nice overview instead of an overwhelmingly big dump like you’d see in a log file.

We focused on the errors most likely to affect you and your users. To do this, we ranked errors by the number of projects experiencing them across different companies. We intentionally looked at the number of projects so that high-volume customers wouldn’t overwhelm the data set with errors that are not relevant to most readers.

Here are the top 10 Rails errors:

Screenshot of Rails Error Statistics

You’ve probably noticed some familiar faces in there already. Let’s dig in and take a look at the errors in a bit more detail to see what might cause them in your production application.

We’ll provide example solutions based on Rails 5, but if you’re still using Rails 4 they should point you in the right direction.

1. ActionController::RoutingError

We start with a classic of any web application, the Rails version of the 404 error. An ActionController::RoutingError means that a user has requested a URL that doesn’t exist within your application. Rails will log this and it will look like an error, but for the most part it is not the fault of your application.

It may be caused by incorrect links pointing at or from within your application. It may also be a malicious user or bot testing your application for common weaknesses. If that’s the case, you might find something like this in your logs:

ActionController::RoutingError (No route matches [GET] "/wp-admin"):

There is one common reason you might get an ActionController::RoutingError that is caused by your application and not by errant users: if you deploy your application to Heroku, or any platform that doesn’t allow you to serve static files, then you might find that your CSS and JavaScript doesn’t load. If this is the case, the errors will look like this:

ActionController::RoutingError (No route matches [GET] "//cdn.rollbar.com/assets/application-eff78fd93759795a7be3aa21209b0bd2.css"):

To fix this and allow Rails to serve static assets you need to add a line to your application’s config/environments/production.rb file:

Rails.application.configure do
  # other config
  config.public_file_server.enabled = true
end

If you aren’t interested in logging 404 errors caused by ActionController::RoutingError then you can avoid them by setting a catch all route and serving the 404 yourself. This method is suggested by the lograge project . To do so, add the following at the bottom of your config/routes.rb file:

Rails.application.routes.draw do
  # all your other routes
  match '*unmatched', to: 'application#route_not_found', via: :all
end

Then add the route_not_found method to your ApplicationController:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def route_not_found
    render file: Rails.public_path.join('404.html'), status: :not_found, layout: false
  end
end

Before implementing this, you should consider whether knowing about 404 errors is important to you. You should also keep in mind that any route or engine that is mounted after the application loads won’t be reachable as they will be caught by the catch all route.

2. NoMethodError: undefined method ‘[]’ for nil:NilClass

This means that you are using square bracket notation to read a property from an object, but the object is missing, or nil, and thus it does not support this method. Since we are working with square brackets, it’s likely that we’re digging through hashes or arrays to access properties and something along the way was missing. This could happen when you’re parsing and extracting data from a JSON API or a CSV file, or just getting data from nested parameters in a controller action.

Consider a user submitting address details through a form. You might expect your parameters to look like this:

{ user: { address: { street: '123 Fake Street', town: 'Faketon', postcode: '12345' } } }

You might then access the street by calling params[:user][:address][:street]. If no address was passed then params[:user][:address] would be nil and calling for [:street] would raise a NoMethodError.

You could perform a nil check on each parameter and return early using the && operator, like so:

street = params[:user] && params[:user][:address] && params[:user][:address][:street]

While that will do the job, thankfully there is now a better way to access nested elements in hashes, arrays and event objects like ActionController::Parameters. Since Ruby 2.3, hashes, arrays and ActionController::Parameters have the dig method. dig allows you to provide a path to the object you want to retrieve. If at any stage nil is returned, then dig returns nil without throwing a NoMethodError. To get the street from the parameters above you can call:

street = params.dig(:user, :address, :street)

You won’t get any errors from this, though you do need to be aware that street may still be nil.

As an aside, if you are also digging through nested objects using dot notation, you can do this safely in Ruby 2.3 too, using the safe navigation operator. So, rather than calling

street = user.address.street

and getting a NoMethodError: undefined method street for nil:NilClass, you can now call.

street = user&.address&.street

The above will now act the same as using dig. If the address is nil then street will be nil and you will need to handle the nil when you later refer to the street. If all the objects are present, street will be assigned correctly.

While this suppresses errors from being shown to the user, if it still impacts user experience, you might want to create an internal error to track either in your logs or in an error tracking system like Rollbar so you have visibility to fix the problem.

If you are not using Ruby 2.3 or above you can achieve the same as above using the ruby_dig gem and ActiveSupport’s try to achieve similar results.

3. ActionController::InvalidAuthenticityToken

Number 3 on our list requires careful consideration as it is related to our application’s security. ActionController::InvalidAuthenticityToken will be raised when a POST, PUT, PATCH, or DELETE request is missing or has an incorrect CSRF (Cross Site Request Forgery) token.

CSRF is a potential vulnerability in web applications in which a malicious site makes a request to your application on behalf of an unaware user. If the user is logged in their session cookies will be sent along with the request and the attacker can execute commands as the user.

Rails mitigates CSRF attacks by including a secure token in all forms that is known and verified by the site, but can’t be known by a third party. This is performed by the familiar ApplicationController line

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
end

So, if your production application is raising ActionController::InvalidAuthenticityToken errors it could mean that an attacker is targeting the users of your site, but the Rails security measures are keeping you safe.

There are other reasons you may be unintentionally receiving this error though.

Ajax

For example, if you are making Ajax requests from your front end, you need to ensure you are including the CSRF token within the request. If you are using jQuery and the built in Rails unobtrusive scripting adapter then this is already handled for you. If you want to handle Ajax another way, say using the Fetch API, you’ll need to ensure you include the CSRF token. For either approach, you need to make sure your application layout includes the CSRF meta tag in the <head> of the document:

<%= csrf_meta_tags %>

This prints out a meta tag that looks like this:

<meta name='csrf-token' content='THE-TOKEN'>

When making an Ajax request, read the meta tag content and add it to the headers as the X-CSRF-Token header.

const csrfToken = document.querySelector('[name="csrf-token"]').getAttribute('content');
fetch('/posts', {
  method: 'POST',
  body: JSON.stringify(body),
  headers: {
    'Content-Type': 'application/json'
    'X-CSRF-Token': csrfToken
  }
).then(function(response) {
  // handle response
});

Webhooks/APIs

Sometimes there are valid reasons to turn off the CSRF protection. If you expect to receive incoming POST requests to certain URLs in your application from third parties, you won’t want to block them on the basis of CSRF. You might be in this position if you are building an API for third party developers or if you expect to receive incoming webhooks from a service.

You can turn off CSRF protection, but make sure you are whitelisting the endpoints you know don’t need this kind of protection. You can do so in a controller by skipping the authentication:

class ApiController < ApplicationController
  skip_before_action :verify_authenticity_token
end

If you are accepting incoming webhooks, you should be able to verify that the request came from a trusted source in place of verifying the CSRF token.

4. Net::ReadTimeout

The Net::ReadTimeout is raised when it takes Ruby longer to read data from a socket than the read_timeout value, which is 60 seconds by default. This error can be raised if you are using Net::HTTP, open-uri or HTTParty to make HTTP requests.

Notably, this doesn’t mean that an error will be thrown if the request itself takes longer than the read_timeout value, just that if a particular read takes longer than the read_timeout. You can read more about Net::HTTP and timeouts from Felipe Philipp.

There are a couple of things we can do to stop getting Net::ReadTimeout errors. Once you understand the HTTP requests that are throwing the error you can try to adjust the read_timeout value to something more sensible. As in the article above, if the server you are making the request to takes a long time to put together a response before sending it all at once, you will want a longer read_timeout value. If the server returns the response in chunks then you will want a shorter read_timeout.

You can set read_timeout by setting a value in seconds on the respective HTTP client you are using:

with Net::HTTP

http = Net::HTTP.new(host, port, read_timout: 10)

with open-uri

open(url, read_timeout: 10)

with HTTParty

HTTParty.get(url, read_timeout: 10)

You can’t always trust another server to respond within your expected timeouts. If you can run the HTTP request in a background job with retries, like Sidekiq, that can mitigate the errors from the other server. You will need to handle the case where the server never responds in time though.

If you need to run the HTTP request within a controller action, then you should be rescuing the Net::ReadTimeout error and providing your user with an alternative experience and tracking it in your error monitoring solution. For example:

def show
  @post = Post.find(params[:slug])
  begin
    @comments = HTTParty.get(COMMENTS_SERVER, read_timeout: 10)
  rescue Net::ReadTimeout => e
    @comments = []
  @error_message = "Comments couldn't be retrieved, please try again later."
    Rollbar.error(e);
  end
end

5. ActiveRecord::RecordNotUnique: PG::UniqueViolation

This error message is specifically for PostgreSQL databases, but the ActiveRecord adapters for MySQL and SQLite will throw similar errors. The issue here is that a database table in your application has a unique index on one or more fields and a transaction has been sent to the database that violates that index. This is a hard problem to solve completely, but let’s look at the low hanging fruit first.

Imagine you’ve created a User model and, in the migration, ensured that the user’s email address is unique. The migration might look like this:

class CreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users do |t|
      t.string :email
      t.timestamps
    end
    add_index :users, :email, unique: true
  end
end

To avoid most instances of ActiveRecord::RecordNotUnique you should add a uniqueness validation to your User model too.

class User < ApplicationRecord
  validates_uniqueness_of :email
end

Without this validation, all email addresses will be sent to the database when calling User#save and will raise an error if they aren’t unique. However, the validation can’t guarantee that this won’t happen. For a full explanation you should read the concurrency and integrity section of the validates_uniqueness_of documentation. The quick description is that the Rails uniqueness check is prone to race conditions based on the order of operation for multiple requests. Being a race condition, this also makes this error hard to reproduce locally.

To deal with this error requires some context. If the errors are caused by a race condition, that may be because a user has submitted a form twice by mistake. We can try to mitigate that issue with a bit of JavaScript to disable the submit button after the first click. Something a bit like this is a start:

const forms = document.querySelectorAll('form');
Array.from(forms).forEach((form) => {
  form.addEventListener('submit', (event) => {
    const buttons = form.querySelectorAll('button, input[type=submit]')
    Array.from(buttons).forEach((button) => {
      button.setAttribute('disabled', 'disabled');
    });
  });
});

This tip on Coderwall to use ActiveRecord’s first_or_create! along with a rescue and retry when the error is raised is a neat workaround. You should continue to log the error with your error monitoring solution so that you maintain visibility on it.

def self.set_flag( user_id, flag )
  # Making sure we only retry 2 times
  tries ||= 2
  flag = UserResourceFlag.where( :user_id => user_id , :flag => flag).first_or_create!
rescue ActiveRecord::RecordNotUnique => e
  Rollbar.error(e)
  retry unless (tries -= 1).zero?
end

ActiveRecord::RecordNotUnique might seem like an edge case, but it’s here at number 5 in this top 10, so it is definitely worth considering with regard to your user experience.

6. NoMethodError: undefined method ‘id’ for nil:NilClass

NoMethodError appears again, though this time with a different explanatory message. This error usually sneaks up around the create action for an object with a relation. The happy path—creating the object successfully—usually works, but this error pops up when validations fail. Let’s take a look at an example.

Here’s a controller with actions to create an application for a course.

class CourseApplicationsController < ApplicationController
  def new
    @course_application = CourseApplication.new
    @course = Course.find(params[:course_id])
  end
  def create
    @course_application = CourseApplication.new(course_application_params)
    if @course_application.save
      redirect_to @course_application, notice: 'Application submitted'
    else
      render :new
    end
  end
  private
  def course_application_params
    params.require(:course_application).permit(:name, :email, :course_id)
  end
end

The form in the new template looks a bit like this:

<%= form_for [@course, @course_application] do |ca| %>
  <%# rest of the form %>
<% end %>

The problem here is when you call render :new from the create action, the @course instance variable wasn’t set. You need to ensure that all the objects the new template needs are initialised in the create action as well. To fix this error, we’d update the create action to look like this:

  def create
    @course_application = CourseApplication.new(course_application_params)
    if @course_application.save
      redirect_to @course_application, notice: 'Application submitted'
    else
      @course = Course.find(params[:course_id])
      render :new
    end
  end

Check out this article if you are interested in learning more about the problems with nil in Rails and how to avoid them.

7. ActionController::ParameterMissing

This error is part of the Rails strong parameters implementation. It does not manifest as a 500 error though—it is rescued by ActionController::Base and returned as a 400 Bad Request.

The full error might look like this:

ActionController::ParameterMissing: param is missing or the value is empty: user

This will be accompanied by a controller that might look a bit like this:

class UsersController < ApplicationController
  def create
    @user = User.new(user_params)
    if @user.save
      redirect_to @user
    else
      render :new
    end
  end
  private
  def user_params
    params.require(:user).permit(:name, :email)
  end
end

The params.require(:user) means that if user_params is called and params does not have a :user key or params[:user] is empty, ActionController::ParameterMissing will be raised.

If you are building an application to be used via a web front end and you have built a form to correctly post the user parameters to this action, then a missing user parameter probably means someone is messing with your application. If that is the case, a 400 Bad Request response is likely the best response as you don’t need to cater to potentially malicious users.

If your application is providing an API, then 400 Bad Request is also an appropriate response to a missing parameter.

8. ActionView::Template::Error: undefined local variable or method

This is our only ActionView error in the top 10 and that’s a good sign. The less work the views have to do to render templates the better. Less work leads to fewer errors. We’re still left with this error though, in which a variable or method you expect to exist simply doesn’t.

This crops up most commonly in partials, probably due to the many different ways you can include a partial with local variables on a page. If you have a partial called _post.html.erb that contains a blog post template and an instance variable @post set in your controller, then you can render the partial like this:

<%= render @post %>

or

<%= render 'post', post: @post %>

or

<%= render partial: 'post', locals: { post: @post } %>

Rails likes to give us plenty of options to work with, but the second and third options here are where confusion can creep in. Trying to render a partial like:

<%= render 'post', locals: { post: @post } %>

or

<%= render partial: 'post', post: @post %>

will leave you with an undefined local variable or method. To avoid this, stay consistent and always render partials with the explicit partial syntax, expressing the local variables in a locals hash:

<%= render partial: 'post', locals: { post: @post } %>

There is one other place you can slip up with local variables in partials. If you only sometimes pass a variable to a partial, testing for that variable is different within a partial to regular Ruby code. If, for example, you update the post partial above to take a local variable that tells you whether to show a header image in the partial, you would render the partial like so:

<%= render partial: 'post', locals: { post: @post, show_header_image: true } %>

Then the partial itself might look like this:

<h1><%= @post.title %></h1>
<%= image_tag(@post.header_image) if show_header_image %>
<!-- and so on -->

This will work fine when you pass the show_header_image local variable, but when you call

<%= render partial: 'post', locals: { post: @post } %>

it will fail with an undefined local variable. To test for the existence of a local variable inside a partial, you should check whether it is defined before you use it.

<%= image_tag(@post.header_image) if defined?(show_header_image) && show_header_image %>

Even better though, there is a hash called local_assigns within a partial that we can use instead.

<%= image_tag(@post.header_image) if local_assigns[:show_header_image] %>

For variables that aren’t booleans, we can use other hash methods like fetch to handle this gracefully. Using show_header_image as an example, this scenario would also work:

<%= image_tag(@post.header_image) if local_assigns.fetch(:show_header_image, false) %>

Overall, watch out when you are passing variables to partials!

9. ActionController::UnknownFormat

This error, like the ActionController::InvalidAuthenticityToken, is one that could be caused by careless or malicious users rather than your application. If you’ve built an application in which the actions respond with HTML templates and someone requests the JSON version of the page, you will find this error in your logs, looking a bit like this:

ActionController::UnknownFormat (BlogPostsController#index is missing a template for this request format and variant.
request.formats: ["application/json"]
request.variant: []):

The user will receive a 406 Not Acceptable response. In this case they’ll see this error because you haven’t defined a template for this response. This is a reasonable response, since if you don’t want to return JSON, their request was not acceptable.

You may, however, have built your Rails application to respond to regular HTML requests and more API-like JSON requests in the same controller. Once you start doing this, you define the formats you do want to respond to and any formats that fall outside of that will also cause an ActionController::UnknownFormat, returning a 406 status. Let’s say you have a blog posts index that looks like:

class BlogPostsController < ApplicationController
  def index
    respond_to do |format|
      format.html { render :index }
    end
  end
end

Making a request for the JSON would result in the 406 response and your logs would show this less expressive error:

ActionController::UnknownFormat (ActionController::UnknownFormat):

The error this time doesn’t complain about a lack of a template—it’s an intentional error because you have defined the only format to respond to is HTML. What if this is unintentional though?

It’s common to miss a format in a response that you intend to support. Consider an action in which you want to respond to HTML and JSON requests when creating a blog post, so that your page can support an Ajax request. It might look like this:

class BlogPostsController < ApplicationController
  def create
    @blog_post = BlogPost.new(blog_post_params)
    respond_to do |format|
      if @blog_post.save
        format.html { redirect blog_post_path(@blog_post) }
        format.json { render json: @blog_post.to_json }
      else
        render :new
      end
    end
  end
end

The error here is raised in the case of the blog post failing validations and not saving. Within the respond_to block, you need to call render within the scope of the format blocks. Rewriting this to accommodate for failure would look like:

class BlogPostsController < ApplicationController
  def create
    @blog_post = BlogPost.new(blog_post_params)
    respond_to do |format|
      if @blog_post.save
        format.html { redirect blog_post_path(@blog_post) }
        format.json { render json: @blog_post.to_json }
      else
        format.html { render :new }
        format.json { render json: @blog_post.errors.to_json }
      end
    end
  end
end

Now all of the formats are covered and there won’t be any more unintentional ActionController::UnknownFormat exceptions.

10. StandardError: An error has occurred, this and all later migrations canceled

This last item on our top 10 disappoints me slightly. StandardError is the base error class that all other errors should inherit from, so using it here makes the error feel very generic, when in reality it is an error that has happened during a database migration. I would prefer to see this error as a descendent of the ActiveRecord::MigrationError. But I digress…

There are a number of things that can cause a migration to fail. Your migrations may have gotten out of sync with your actual production database, for example. In that case, you’re going to have to go digging around to find out what has happened and fix it.

There is one thing that should be covered here though: data migrations.

If you need to add or calculate some data for all the objects in a table you might think that a data migration is a good idea. As an example, if you wanted to add a full name field to a user model that included their first and last name (not a likely change, but good enough for a simple example), you might write a migration like this:

class AddFullNameToUser < ActiveRecord::Migration
  def up
    add_column :users, :full_name, :string
    User.find_each do |user|
      user.full_name = "#{user.first_name} #{user.last_name}"
      user.save!
    end
  end
  def down
    remove_column :users, :full_name
  end
end

There are a lot of problems with this scenario. If there is a user with corrupt data in y x xour set, the user.save! command will throw an error and cancel the migration. Secondly, in production you may have a lot of users, which means the database would take a long time to migrate, possibly keeping your application offline for the entire time. Finally, as your application changes over time, you might remove or rename the User model, which would cause this migration to fail. Some advice suggests that you define a User model within the migration to avoid this. For even greater safety, Elle Meredith advises us to avoid data migrations within ActiveRecord migrations completely and build out temporary data migration tasks instead.

Changing data outside of the migration ensures you do a few things. Most importantly, it makes you consider how your model works if the data is not present. In our full name example, you would likely define an accessor for the full_name property that could respond if the data was available. If it’s not, then build the full name by concatenating the constituent parts.

class User < ApplicationRecord
  def full_name
    @full_name || "#{first_name} #{last_name}"
  end
end

Running a data migration as a separate task also means the deploy no longer relies on this data changing across the production database. Elle’s article has more reasons why this works better and includes best practices on writing the task as well.

Conclusion

The most popular Rails errors can come from anywhere within the application. In this article we’ve seen common errors manifested in the model, the view, and the controller. Some of the errors aren’t necessarily anything to worry about and are just protecting your application. Others should be caught as soon as possible and stamped out.

Nevertheless, it’s good to track how often these errors happen. This leads to better visibility into problems that are affecting your users or application security, so you can fix them quickly. Otherwise, these error messages will be shown to the user, but the engineering and product management teams will have no idea until users complain to support.

We hope you learned something new and are better equipped to avoid these errors in the future. However, even with the best practices, unexpected errors do pop up in production. It’s important to have visibility into errors that affect your users, and to have good tools to solve them quickly.

Rollbar gives you visibility to production Ruby errors, which offers more context to solve them quickly, including form validation errors, person tracking, boot errors and more. Check out Rollbar’s full list of features and Ruby SDK documentation.


If you haven’t already, sign up for a 14-day free trial of Rollbar and let us help you take control of impactful Rails errors.

[email protected]:~/library$ rake db:migrate

== 20180407084831 Books: migrating ============================================
— create_table(:books)
rake aborted!
StandardError: An error has occurred, all later migrations canceled:

Mysql2::Error: Table 'books' already exists: CREATE TABLE `books` (`id` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY, `title` varchar(32) NOT NULL, `price` float, `subject_id` int, `description` text, `created_at` timestamp NULL) ENGINE=InnoDB /home/sania/library/db/migrate/20180407084831_books.rb:4:in `up'

Caused by:
ActiveRecord::StatementInvalid: Mysql2::Error: Table ‘books’ already exists: CREATE TABLE books (id bigint NOT NULL AUTO_INCREMENT PRIMARY KEY, title varchar(32) NOT NULL, price float, subject_id int, description text, created_at timestamp NULL) ENGINE=InnoDB
/home/sania/library/db/migrate/20180407084831_books.rb:4:in `up’

Caused by:

Mysql2::Error: Table 'books' already exists
/home/sania/library/db/migrate/20180407084831_books.rb:4:in `up'
Tasks: TOP => db:migrate

(See full trace by running task with —trace)


This is the content of 20180407084831_books.rb file

class Books < ActiveRecord::Migration[5.1]

 def self.up
    create_table :books do |t|
         t.column :title, :string, :limit => 32, :null => false
         t.column :price, :float
         t.column :subject_id, :integer
         t.column :description, :text
         t.column :created_at, :timestamp
      end
   end

   def self.down
      drop_table :books
   end

end

This is the content of 20180407072616_create_books.rb file

class CreateBooks < ActiveRecord::Migration[5.1]
  def change
    create_table :books do |t|

      t.timestamps
    end
  end
end

Please help me with the solution. I am new to rails. I have also tried dropping the db but rakes aborts with the following error

rake aborted!
ActiveRecord::NoEnvironmentInSchemaError:

Environment data not found in the schema. To resolve this issue, run:

    bin/rails db:environment:set RAILS_ENV=development

I am unable to understand the cause of it. Please help me explain. Thanks in advance

Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

So I was trying to migrate my code with bin/rake db:migrate and instead I wound up with something like this.

~/workspace/projects/odot (master) $ bin/rake db:migrate --trace
Running via Spring preloader in process 1736
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
[DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.
** Invoke db:migrate (first_time)
** Invoke environment (first_time)
** Execute environment
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:migrate
== 20160629023110 CreateTodoLists: migrating ==================================
-- create_table(:todo_lists)
rake aborted!
StandardError: An error has occurred, this and all later migrations canceled:

undefined method `To' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x00000004e63fa8>
/home/ubuntu/workspace/projects/odot/db/migrate/20160629023110_create_todo_lists.rb:4:in `block in change'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/schema_statements.rb:216:in `create_table'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:665:in `block in method_missing'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:634:in `block in say_with_time'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/benchmark.rb:293:in `measure'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:634:in `say_with_time'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:654:in `method_missing'
/home/ubuntu/workspace/projects/odot/db/migrate/20160629023110_create_todo_lists.rb:3:in `change'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:608:in `exec_migration'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/benchmark.rb:293:in `measure'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:591:in `block in migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:590:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:768:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:1044:in `block in ddl_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `block in transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/transaction.rb:184:in `within_new_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/transactions.rb:220:in `transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:1044:in `ddl_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:959:in `block in migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:823:in `up'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:801:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/tasks/database_tasks.rb:137:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:152:in `invoke_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block in top_level'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:117:in `run_with_threads'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:102:in `top_level'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:80:in `block in run'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:77:in `run'
/home/ubuntu/workspace/projects/odot/bin/rake:9:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
-e:1:in `<main>'
NoMethodError: undefined method `To' for #<ActiveRecord::ConnectionAdapters::TableDefinition:0x00000004e63fa8>
/home/ubuntu/workspace/projects/odot/db/migrate/20160629023110_create_todo_lists.rb:4:in `block in change'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/schema_statements.rb:216:in `create_table'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:665:in `block in method_missing'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:634:in `block in say_with_time'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/benchmark.rb:293:in `measure'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:634:in `say_with_time'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:654:in `method_missing'
/home/ubuntu/workspace/projects/odot/db/migrate/20160629023110_create_todo_lists.rb:3:in `change'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:608:in `exec_migration'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:592:in `block (2 levels) in migrate'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/benchmark.rb:293:in `measure'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:591:in `block in migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/connection_pool.rb:292:in `with_connection'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:590:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:768:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:998:in `block in execute_migration_in_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:1044:in `block in ddl_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `block in transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/transaction.rb:184:in `within_new_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/connection_adapters/abstract/database_statements.rb:213:in `transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/transactions.rb:220:in `transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:1044:in `ddl_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:997:in `execute_migration_in_transaction'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:959:in `block in migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:955:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:823:in `up'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/migration.rb:801:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/tasks/database_tasks.rb:137:in `migrate'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-4.2.6/lib/active_record/railties/databases.rake:44:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:248:in `block in execute'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:243:in `execute'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:187:in `block in invoke_with_call_chain'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/monitor.rb:214:in `mon_synchronize'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:180:in `invoke_with_call_chain'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/task.rb:173:in `invoke'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:152:in `invoke_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block (2 levels) in top_level'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:108:in `block in top_level'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:117:in `run_with_threads'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:102:in `top_level'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:80:in `block in run'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:178:in `standard_exception_handling'
/usr/local/rvm/gems/ruby-2.3.0/gems/rake-11.2.2/lib/rake/application.rb:77:in `run'
/home/ubuntu/workspace/projects/odot/bin/rake:9:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `block in load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:240:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-4.2.6/lib/active_support/dependencies.rb:268:in `load'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
/usr/local/rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
-e:1:in `<main>'
Tasks: TOP => db:migrate

So I was curious as to what exactly was the cause of this? From what I’ve seen online, I either have a software issue with one of the gems like rake or spring. Or there’s an issue with the string for my scaffold. I’m unsure exactly what it is at this moment. Any ideas?

3 Answers

Stephen Fricke July 6, 2016 3:26am

Yeah. Here it is.

class CreateTodoLists < ActiveRecord::Migration
  def change
    create_table :todo_lists do |t|
      t.To :title
      t.string :Do
      t.text :List

      t.timestamps null: false
    end
  end
end

Abhishek Sisodia

Problem here is in line 4 & 5.
they should read

here
t refers to the todo_lists table generated by create_table method,
:title refers to the name of column, and
string refers to the datatype of the column.

If this migration file was auto generated by your scaffold command, then closely compare what you wrote with

bin/rails generate scaffold todo_list title:string description:text

Stephen Fricke July 6, 2016 4:36pm

Yeah, I see what I did wrong now. I had case of confusion with :string description: when generating the scaffold. It works now.

(Syntax, Syntax….SYNTAX).

Thanks for the help.

Понравилась статья? Поделить с друзьями:
  • R6034 как исправить gta sa
  • Railgrade fatal error
  • R6030 crt not initialized как исправить windows 7
  • Raidcall ошибка flashctrl error
  • R6030 crt not initialized как исправить fallout