ユーザーが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