samedi 4 juillet 2020

how to send row id to another table while importing data from excel file in rails applicaiton

stage table has one_to_many association with task table. task table has attribute stage_id.
In my excel file there is parent child ID column like 1,2,3,4 is stage and 1.1,1.2..4.1..so on is task.

i want to import that file but the problem is how i'll take stage_id of new created row and put them is task table. so that while retrieving data no problem is faced.

if there is alternate easy solution to solve such problem please provide that solution. I have to save that in order, so that i can identify which has child and which is parent also there order.

stage.rb

  def self.import(file)
    accessible_attributes = ['stage','planned_start_date', 'planned_end_date', 'actual_start_date', 'actual_end_date']
    spreadsheet = Roo::Spreadsheet.open(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      stage =Stage.find_by_id(row["id"]) || new
      stage.attributes = row.to_hash.slice(*accessible_attributes)
      stage.save!
    end
  end

  def open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::CSV.new(file.path, csv_options: {encoding: "SJIS"})
    when ".xls" then Roo::Excel.new(file.path, nil, :ignore)
    when ".xlsx" then Roo::Excelx.new(file.path, nil, :ignore)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

index.html.erb

<%= form_tag import_project_stages_path(@project), multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import", :class=>"button warning" %>
<%end %>

Aucun commentaire:

Enregistrer un commentaire