/public
folder as car_data.csv
rails new data_loader
rails g scaffold Car year:integer make:string model:string vin:string
Use this syntax
rails g task <namespace> <task name 1> <task name 2> <task name 3>
Where
namespace
is a grouping. This could be namedmorning
, orweekly
or whatever best suits your needs
However, in our case, we're only creating one task, therefore:
rails g task initial load_cars
Running this will generate the following file: lib/tasks/initial.rake
Open this file and make it look like so:
namespace :initial do
desc "TODO"
task load_cars: :environment do
require 'csv'
CSV.foreach('public/car_data.csv', :headers => true) do |row|
Car.create!(row.to_hash)
end
puts "All cars were loaded"
end
end
Some things to note:
:headers => true
in the task.'public/car_data.csv'
. We can specify any path. It just needs to be accessible and has to be validrake initial:load_cars
Wait a second! That looks very similar to something we've done throughout the course, correct?
As a final check, you can now use the rails console to see that your data loaded
rails c
and
2.0.0-p481 :001 > Car.all
http://railsguides.net/how-to-generate-rake-task/
http://jasonseifer.com/2010/04/06/rake-tutorial
http://tutorials.jumpstartlab.com/topics/systems/automation.html