简体   繁体   中英

Custom headers for rails 4 CSV Import

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

You can create a method to replace the header yourself. Read the file into memory, altering the first line. Then run the CSV.foreach . I'm sure there's a better way to indent this...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM