Joe Gatt
Joe Gatt

Reputation: 2235

Rails: running an initializer after migrate

I have some code which I run from an initializer and it works fine. (It saves default settings from a yaml file to the database for the rails-settings-cache gem.)

But when I run this on Travis CI, since it is doing a migration from scratch, the initializer fails because the table does not exist yet.

Is there a way of running code after the migration but before the application starts?

Upvotes: 4

Views: 1648

Answers (1)

Peter Goldstein
Peter Goldstein

Reputation: 4545

So while I don't love doing this, an easy way to prevent the initializer from running during db:migrate, but running on application start or test run is to wrap it in a clause testing if the table exists. So if you take your existing initializer code and wrap it in

if ActiveRecord::Base.connection.table_exists? 'table_name'
   ....
end

where 'table_name' is the name of the missing table, then both rake db:migrate and the spec run should be able to complete successfully.

Upvotes: 14

Related Questions