简体   繁体   English

Rails 4 - 导入CSV无效

[英]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. 在rails 4.2.4中,我试图从.csv文件中提取数据并将其保存到数据库中。 But right now extracted row from the file is in wrong format so that value is not getting save. 但是现在从文件中提取的row格式错误,因此值不会保存。

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"] . 生成的row数据类似于["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. 从这row我没有分别得到每个值Eg: row[0], row[1] & row[2]来分配相关的数据库字段。

How can I solve this CSV import issue? 如何解决此CSV导入问题? 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. CSV文件使用tab作为列分隔符。 You can pass your own column separator to CSV as a col_sep option. 您可以将自己的列分隔符作为col_sep选项传递给CSV Even though other 2 answers will do the job, let csv do its job on its own: 即使其他2个答案都可以完成这项工作,让csv完成它的工作:

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] : 另外,考虑使用headers选项将文件的第一行用作标题而不是[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. CSV代表逗号分隔值。 It seems that your file is separated by spaces instead. 您的文件似乎用空格分隔。 Replace the tabs in your file by commas. 用逗号替换文件中的选项卡。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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