简体   繁体   中英

Rails 4 - Import CSV is not working

In rails 4.2.4, I am trying to extract the data from .csv file and save it to the database. But right now extracted row from the file is in wrong format so that value is not getting save.

require 'csv'
filename = "#{asset.document.path}"
if File.exist?(filename)
  file = File.open(filename)
  if file
    CSV::parse(file)[1..-1].each do |row|
      User.create_data(row, admin)
    end
  end
end

def create_data(row, admin)
  usr = User.new
  usr.name = row[0] if row[0]
  usr.email = row[1] if row[1]
  usr.password = row[2] if row[2]
  user.save
end

Generated row 's data is like ["Sannidhi\\tsannidhi@gmail.com\\tsannidhi123@\\t"] . From this row I am not getting each values separately Eg: row[0], row[1] & row[2] to assign for related database fields.

How can I solve this CSV import issue? Please help me.

Try this:

CSV::parse(file)[1..-1].each do |row|
  row.shift.split("\t") unless row.blank?
  User.create_data(row, admin)
end

After this, you should be able to access:

row[0] #=> "Sannidhi"
row[1]
row[2]

You CSV file uses tab s as column separators. You can pass your own column separator to CSV as a col_sep option. Even though other 2 answers will do the job, let csv do its job on its own:

CSV::parse(file, col_sep: "\t")[1..-1].each do |row|
  User.create_data(row, admin)
end

Also, consider using headers option to use the first line of the file as a header instead of [1..-1] :

CSV::parse(file, col_sep: "\t", headers: 'first_row').each do |row|
  User.create_data(row, admin)
end

CSV stands for Comma Separated Value. It seems that your file is separated by spaces instead. Replace the tabs in your file by commas.

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