Rake sequential tasks

2019-08-16 07:44发布

I have run into a very strange problem. I have a task which resets my database as so:

task :reset => [:drop, :create, :migrate, :seed]

The problem is, I am receiving errors when seeding because of missing columns which are added in late migration files. One example:

undefined method new_attr= for User

Yet this attribute is already added in a migration. The strange part is, I receive no errors if I run the above tasks separately. Can anybody shed some light? Surely these tasks cannot be run asynchronously.

Another way to avoid errors is to amend my earlier migrations create_ with the new attributes. Then running :reset doesn't trigger errors for those attributes.

The migrations are clearly fine as I can run the above tasks separately, just not bundled under a single task.

3条回答
乱世女痞
2楼-- · 2019-08-16 08:14

If these rake tasks are executed in the production mode, model attributes are cached. Even though migrations work perfect, it wont apply to the cached. This will break your succeeding seed as newly added columns will be missing in the cache. A possible solution is to reload your rails environment before seeding.

查看更多
闹够了就滚
3楼-- · 2019-08-16 08:21

maybe you want to make your reset task more explicit?

namespace :db_tasks do
  desc "Rebuild development db"
  task :rebuild_database, [] => :environment do
    raise "Only run in development or staging" if Rails.env.production?

    Rake::Task['db:drop'].execute
    Rake::Task['db:create'].execute
    Rake::Task['db:migrate'].execute
    Rake::Task['db:seed'].execute
    Rake::Task['db:test:prepare'].execute
  end
end
查看更多
Bombasti
4楼-- · 2019-08-16 08:21

Probably your problem is already solved using this:

rake db:reset

The rake db:reset task will drop the database, recreate it and load the current schema into it.

Have you tried with namespace?

task :reset => [db:drop, db:create, db:migrate, db:seed]

查看更多
登录 后发表回答