DEV Community

chair
chair

Posted on

CSV on Rails

Video Guide on YouTube

Using csv's you can quickly jumpstart your rails app with mock data and help you hit the ground running in your development process.

This post will teach you how to:

  1. Spin up a new rails app with postgresql database.
  2. Create a mock data csv with help from our friends at mockaroo https://mockaroo.com/ we'll be using car makes and models for this demo.
  3. Create database records from our mock data in our rails app using the ruby CSV class.
  4. Export specific database objects to CSV.

Resource Links:

Mockaroo

New rails app

Ruby CSV Class

Lets get going!

First lets spin up our new rails app:
rails new my_car_app --database=postgresql

cd into your app's directpry and run bundle to ensure all our gems are loaded:
bundle

Next lets scaffold a new car model with all the accouterments:
rails generate scaffold Car make:string model:string model_year:integer factory_id:string

Setup and migrate your database:
rails db:setup
then
rails db:migrate

Hop into the rails console, from the home directory of your app run:
rails console

Run a count on the car model to prove there are indeed, 0 cars:
Car.count

Lets create a car using the "create" method defined in our cars controller:
Car.create!

Awesome! We have a car. It is a bit bland though, not much data to be had apart from nil values for the interesting bits.

This is where mockaroo helps us out! Hope over to https://mockaroo.com and create the fields like so:

Mockaroo Example

Place the mock data csv file with the mock data in the app/tmp/ directory.

Now lets create a new file in your app's home directory named create_cars.rb.

require 'csv'

CSV.foreach("tmp/car_mock_data.csv") do |row|
    Car.create!(
        make: row[0],
        model: row[1],
        model_year: row[2],
        factory_id: row[3]
    )
end

Enter fullscreen mode Exit fullscreen mode

We are now prepared to create 1000 new cars! In your bash terminal from your app's home directory run:
rails r create_cars.rb

Hop back into your rails console:
rails c

Confirm we we have 1001 cars now:
Car.count

Now, lets say we would like to create a csv containing only Japanese made car models?

Lets create another file in our app's home directory, called japanese_cars.rb.

require 'csv'

japanese_car_makes = [
  "Toyota",
  "Suzuki",
  "Nissan",
  "Infiniti",
  "Mazda",
  "Lexus",
  "Mitsubishi",
  "Isuzu",
  "Subaru",
  "Acura",
  "Honda",
  "Scion",
];

path = 'tmp/japanese_cars.csv';

CSV.open(path, "wb") do |csv|
  # headers
  csv << ["Make", "Model", "Year", "Facory ID"]

  Car.where(make: japanese_car_makes).find_each do |car|
    begin
      # data rows
      csv << [car.make, car.model, car.model_year, car.factory_id]

    rescue Exception => e
      puts Rails.backtrace_cleaner.clean(e.backtrace)
    end
  end
end
Enter fullscreen mode Exit fullscreen mode
  • Up top we require the ruby csv class.
  • Declare an array of Japanese car model names
  • Set a path variable for your csv
  • Begin the csv loop
  • Loop thru cars where the make matches one of the japanese_car_makes indexes.
  • Set the headers
  • Fill in the data rows
  • Handle errors gracefully

And voila! We've covered quite a bit in such a short and easy exercise!

  • The ruby csv class
  • Spin up a new rails app
  • Scaffold a new model, and all accouterments
  • Create database entries from a csv file
  • Create a csv file from specific database entries

Good luck, have fun!

Top comments (0)