Search code examples
ruby-on-railscsvhas-and-belongs-to-many

Create records in has_and_belongs_to_many models from .csv file


I have two spreadsheets of data saved in separate Google spreadsheets, Stores and Products.

Stores has columns for:

  • Store name
  • Store location
  • Store ID

Products has columns for:

  • Product name
  • Product cost
  • Product ID
  • Store ID

In Rails, I have two models - Store and Product - connected with a has_and_belongs_to_many relationship. The models have attributes matching each of the columns in the spreadsheets.

I'm looking to create a rake task that takes the spreadsheets as CSV files and creates linked rows in the Stores and Products databases, but being a coding newbie I'm finding it difficult. Adding data to one table from a .csv seems easy enough, but how can I use the matching "Product ID" column to link the data in the two csv files?


Solution

  • In general I would do something like the following:

    1. Start by creating the stores first as they are independent. As you create the store and save the object, add the store object to a hash of {storeid:}
    2. Then read in the products.csv (I'm assuming that there will be more than one product per store?).
    3. For each row in the product csv, create the product object and then set the association by looking up the store object from your hash with the id in the row you are reading, finally save your product object.

      class Store < ActiveRecord::Base  
      
      end
      
      
      class Product < ActiveRecord::Base  
      
        has_and_belongs_to_many :stores  
      
      end
      

    For rails I would guess that there is a quick way to do this via one of the many tools (rake etc).