3

ユーザーがcsvまたはExcelを介してコンテンツをアップロードする必要がある単純なレールアプリがあります。ユーザーがデータベース内のすべての必須フィールドを知っていると常に想定したいわけではありません。最初の列が必要であり、最初の列に配置されたコンテンツmobile_numberがデータベースの列に入力されることをユーザーに知ってもらいたいだけです。私が話していることの私のコードサンプルは以下のとおりです。私はroo gemを使用しています。シンプルなアプリなので、連絡先テーブルで使用されるデータベース列は 2 つだけです。

  def load_imported_contacts
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      contact = Contact.find_by_id(row["id"]) || Contact.new
      contact.name = "content of the second field(optional)"
      contact.mobile_number = "content in the first(required and must be the first column)"
      contact.save!
    end
  end

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

1 に答える 1

2

いくつかの調査を行った後、私は最終的に私の問題を解決しました。この質問を投稿する前にこれを行うべきでした。解決策は以下です

  def load_imported_contacts
    spreadsheet = open_spreadsheet
    header = spreadsheet.row(1)
    (1..spreadsheet.last_row).map do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      contact = Contact.find_by_id(row["id"]) || Contact.new
      contact.mobile_number = spreadsheet.cell(i,'A')
      contact.name = spreadsheet.cell(i,'B')
      contact
    end
  end
于 2013-04-16T13:16:53.753 に答える