Im adding an import feature to my rails app.. I want to have the ability to import users, however my user table columns are short hand ie. f_name = firs name l_name = last name and so on.. I would like to create an import tool that users can download from the app and fill out to save the time in initial user imports (this will be used for other models as well..) is there any way I can set the import method to read custom headers? I have tried to search this out, but not getting much back. Perhaps its is how I am phrasing the question?
As it sits now the import functionality is working, but who really wants a nasty plain looking excel sheet..
My Import Controller Action:
def import
User.import(params[:file])
redirect_to users_path, notice: 'Users Added Successfully'
end
My import class function:
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
User.create! row.to_hash
end
end
答案 0 :(得分:1)
您可以创建一种方法来自行替换标题。将文件读入内存,改变第一行。然后运行CSV.foreach
。我确信有更好的方法来缩进这个......
def self.headers
{"last name" => "l_name",
"first name" => "f_name"}
end
def self.import(file)
CSV.parse(self.parse_headers(file), headers: true) do |row|
User.create! row.to_hash
end
end
def self.parse_headers (file)
File.open(file) { |f|
first_line = f.readline
self.headers.each { |k,v| first_line[k] &&= v }
first_line + f.read }
end