简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM