我已经提到RailsCasts #396从CSV,XLS xlas文件导入数据。按照railscast(滑轨3.2.9)的导入方法是未定义的局部变量或方法错误的Rails 4.2.6
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 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
但由于Rails的4倍实现强劲PARAMS我得到undefined local variable or method 'accessible_attributes'
错误
所以,我抬头一看,发现这个计算器问题Rails 4 how to call accessible_attributes from Model,根据答案我试过
def attr_names
[user_id, last_name, first_name, last_name_kana, first_name_kana, created_at,created_by, updated_at, updated_by, del_flag]
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]
user = find_by(user_id: row["user_id"]) || new
user.attributes = row.to_hash.slice(*attr_names)
user.save!
end
end
def self.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
还是得到同样的错误,只是这次是undefined local variable or method 'attr_names'
。在此先感谢
你需要'高清self.attr_names' –
@SergioTulentsev谢谢...多么愚蠢的我 !!!! –