I have seen some apps that have a few rake tasks included to load data. I am not talking about seed data, I know about db/seeds.rb, instead I am referring to data such as default users and basic records that help me fill my application with something to look at. I don't want to use db:fixtures:load because I don't have any control over this...
I would like to have rake tasks like this:
rake myapp:data:delete
rake myapp:data:load
rake myapp:data:reload
Where the 'delete' rake task would delete all data that I specify in the rake task, the 'load' app will load the default data from the task into the app and the 'reload' task will delete all data, then load it in the app. How do I do something like this?
If you could give me an example where I have a model named 'Contact' and a few fields - basically how to add or delete data from those fields in a rake task, I would REALLY appreciate it!
Just to give you an idea, I would mainly use these rake tasks when I move from one computer to another to do development. I don't want to manually go enter default records (such as my user to login with) so I could just do rake myapp:data:reload - this would be after doing rake db:schema:load
Thank you,
BN
Create a 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
So now you have defined your rake tasks. I'm using the gem database_cleaner, so you'll need to install it:
sudo gem install database_cleaner
Now, the rake myapp:data:load
is basically loading the data from a file called db/data.rb
. You could name it anything you wanted as long as you used the file name in the rake task or you could use more than one file if you wanted... So create the file db/data.rb
and put all the code that you need...
User.create(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With