Search code examples
ruby-on-railsjoinimport-from-excel

How can I import category_ids from excel file to categories_products join table in rails ?


I have excel file inside a column name category_ids . I need to import to join table, categories_products , from excel file in Rails. How can I do ?


Solution

  •   desc 'import data for models'
      task datas: [:environment] do
    
       categories_sheet = sheet.sheet('category')
       (2..categories_sheet.last_row).each do |j|
        category_row = categories_sheet.row(j)
        category = Category.create!(id: category_row[0], name: 
        category_row[1])
        print category.id
        categories_sheet = sheet.sheet('category')
       end
    
       product_sheet = sheet.sheet('product')
       (2..product_sheet.last_row).each do |j|
        product_row = product_sheet.row(j)
        product = Product.create!(id: product_row[0], 
        name: product_row[1])
        category_ids = product_row[2].split(",")
        product.category_ids = category_ids
        product_sheet = sheet.sheet('product')
    end
    end