2016-08-12 79 views
1

我已經提到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'。在此先感謝

+1

你需要'高清self.attr_names' –

+0

@SergioTulentsev謝謝...多麼愚蠢的我 !!!! –

回答

1

作爲在模型上,你應該讓self.attr_names。另外,所有的方法是有自我,你可以擴展自己,就像這樣:

extend self 

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 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 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 
0

試試這個

user.attributes = row.to_hash.slice(*column_names) 
相關問題