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

83 Views Asked by At

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 belongs_to :category
  • category has_many :products

Product has column category_id

CVS file has the following columns:

  • product_name,
  • category_name,
  • product_price

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!

1

There are 1 best solutions below

3
On BEST ANSWER

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
))