ruby-on-railscvsimport

Rails: insert associated column_id by looking up another column when importing from CSV file


I looked at some issues here on StackOverflow and didn't find my case (which I think strange because my goal seems to be common enough).

I have two models: Products and Categories that are associated as follows:

Product has column category_id

CVS file has the following columns:

How on Earth I can take category_name from the file and insert category_id into the Products table?

I have the following code from Rails-Casts:

  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Response.create! row.to_hash
    end
  end

Thank you!


Solution

  • Not everything has to be done in one line. You can do something like this for each CSV row:

    category_name = row['category_name']
    category = Category.find_by_name(category_name) unless category_name.blank?
    
    Product.create({
      name: row['product_name'],
      price: row['product_price'],
      category: category
    ))