zapatify
12/2/2015 - 10:22 PM

Creating Rake Tasks.md

Creating a rake task to import data

  1. Create your Rails application
  2. Scaffold a resource and attributes
  3. Place this data file in /public folder as car_data.csv
  4. Generate a rake task
  5. Run the rake task
Create rails app
rails new data_loader
Scaffold a resource with attributes
rails g scaffold Car year:integer make:string model:string vin:string
Generate a rake task

Use this syntax

rails g task <namespace> <task name 1> <task name 2> <task name 3>

Where namespace is a grouping. This could be named morning, or weekly 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:

  1. There is a header row in the data file, and we note that with :headers => true in the task.
  2. Notice the file path 'public/car_data.csv'. We can specify any path. It just needs to be accessible and has to be valid
  3. The columns in the sample data match perfectly the attributes of the resource, otherwise our data won't load properly
Finally, call the rake task from the command line

rake 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
Some additional reading on the subject

http://railsguides.net/how-to-generate-rake-task/

http://jasonseifer.com/2010/04/06/rake-tutorial

http://tutorials.jumpstartlab.com/topics/systems/automation.html