Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails initializers are running while migrating database

It is very surprising that Rails's initializers run while running any rake task, including db:migrate and db:seed.

An initializer in my app starts a background thread (a kind of worker process), and it should be executed only when the application is running in debug and production mode.

How to prevent a specific initializer from running when doing rake db:migrate or how to detect in initializer that a rake task is running?

like image 789
Paul Avatar asked Jun 10 '14 08:06

Paul


People also ask

How rails db Migrate works?

A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.

Are rails migrations run in a transaction?

On databases that support transactions with statements that change the schema, migrations are wrapped in a transaction. If the database does not support this then when a migration fails the parts of it that succeeded will not be rolled back. You will have to rollback the changes that were made by hand.

What are Initializers in rails?

An initializer is any file of ruby code stored under /config/initializers in your application. You can use initializers to hold configuration settings that should be made after all of the frameworks and plugins are loaded.

How do I reset migration in rails?

just use rake db:reset , that will drop your database (same as undoing all migrations) and reset to the last schema. UPDATE: a more correct approach will be using rake db:migrate:reset . That will drop the database, create it again and run all the migrations, instead of resetting to the latest schema.


1 Answers

If your initializer depends on the creaton of a specific table, one alternative is to check using ActiveRecord::Base.connection.table_exists? :mytable.

like image 178
Alessandro Gurgel Avatar answered Oct 04 '22 18:10

Alessandro Gurgel