Rake task to add default data

I saw some applications in which several rake tasks were used to load data. I'm not talking about seed data, I know about db / seeds.rb, instead, I mean data like default users and base records that help me fill my application with something to look at. I do not want to use db: fixtures: load, because I have no control over this ...

I would like such tasks to be like this:

rake myapp:data:delete
rake myapp:data:load
rake myapp:data:reload

If the “delete” rake task deletes all the data that I specify in the rake task, the “load” application loads the default data from the task into the application, and the “reload” task deletes all the data, then load it in the application. How do I do something like this?

If you could give me an example where I have a model named “Contact” and several fields - basically, how to add or remove data from these fields in a grabbed task, I would REALLY rate it!

Just to give you an idea, I would mainly use this rake when I switch from one computer to another to do development. I don’t want to manually enter default entries (for example, my user to log in), so I could just do rake myapp: data: reload - this will be after rake db: schema: load

Thank,

B.

+5
source share
1 answer

Create the file lib / tasks / data.rake and write the following code:

require File.join(File.dirname(__FILE__), '../../config/environment')
require 'database_cleaner'

namespace :myapp do
  namespace :data do

    task :delete do
      DatabaseCleaner.strategy = :truncation
      DatabaseCleaner.clean
    end

    task :load do
      require 'db/data.rb'
    end

    task :reload do
      Rake::Task['myapp:data:delete'].invoke
      Rake::Task['myapp:data:load'].invoke
    end

  end
end

, -. gem database_cleaner, :

sudo gem install database_cleaner

rake myapp:data:load db/data.rb. , rake, , ... , db/data.rb ..

User.create(...)
+7

All Articles