jeudi 14 avril 2016

Importing two CSV file to ruby on rails but I want both file to be import on one CSV file all together

My code work fine but I need advise or help on how to import two different CSV file into one CSV file. Foe example product and sales. how do I add the sales attributes into my products CSV files were it take all the sales attributes. '

products/index.html.erb

<h2>Import Products</h2>

<%= form_tag import_products_path, multipart: true do %>
  <%= file_field_tag :file %>
  <%= submit_tag "Import" %>
<% end %>

routes.rb

  resources :products do
      collection { post :import }
    end

products_controller.rb

def import
  Product.import(params[:file])
  redirect_to root_url, notice: "Products imported."
end

products_models.rb

def self.to_csv
    attributes = %w{ name date etc etc   }
    CSV.generate(headers: true) do |csv|
      csv << attributes

      all.each do |script|
        csv << attributes.map{ |attr| script.send(attr) }
      end
    end
  end

def self.import(file)
  spreadsheet = open_spreadsheet(file)
  header = spreadsheet.row(1)
  (2..spreadsheet.last_row).each do |i|
    row = Hash[[header, spreadsheet.row(i)].transpose]
    product = find_by_id(row["id"]) || new
    product.attributes = row.to_hash.slice(*accessible_attributes)
    product.save!
  end
end



 def self.open_spreadsheet(file)
    case File.extname(file.original_filename)
    when ".csv" then Roo::CSV.new(file.path)
    when ".xls" then Roo::CSV.new(file.path)
    when ".xlsx" then Roo::CSV.new(file.path)
    else raise "Unknown file type: #{file.original_filename}"
    end
  end

Also my sales controller and models folder look similar to the above code. The only difference is that sales has different attributes names.So when I upload the file from my product, how to I get the sales attributes without receiving an error message that says unknown attributes when I am trying to upload the sales attributes. thank you.

Aucun commentaire:

Enregistrer un commentaire