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: