[英]rails Import csv file, but saving blank
我的github地址https://github.com/ParkHyunDo/ImportCsv
我正在研究如何使用Roo導入Excel文件。 導入工作正常,但所有內容均為空白。 像這樣....
這是我的代碼
class Product < ActiveRecord::Base
acts_as_xlsx
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(accepts_nested_attributes_for)
product.save!
end
end
def self.open_spreadsheet(file)
case File.extname(file.original_filename)
# You're using a tab seperated file, so specify seperator as a tab with \t
when ".csv" then Roo::CSV.new(file.path, csv_options: {col_sep: "\t"})
when ".xls" then Roo::Excel.new(file.path)
when ".xlsx" then Roo::Excelx.new(file.path)
else raise "Unknown file type: #{file.original_filename}"
end
end
end
def import
Product.import(params[:file])
redirect_to root_url, notice: "Products imported."
end
請幫我!
這行似乎很奇怪:
product.attributes = row.to_hash.slice(accepts_nested_attributes_for)
類方法accepts_nested_attributes_for
具有與列出Product
的屬性名稱完全不同的目的。 但是您可以使用attribute_names
。 嘗試這個:
product.attributes = row.to_hash.stringify_keys.slice(*attribute_names)
注意, stringify_keys
可能是不必要的,具體取決於row.to_hash
返回的哈希row.to_hash
外觀。 還要注意,slice包含屬性名稱列表,而不是數組。 星號*
允許我們將數組的元素用作函數的單獨參數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.