我希望将带有标题的CSV文件导入Rails应用程序。我的模型中有以下内容:
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
puts(*attribute_names)
puts(row.to_hash)
@distrib = Distrib.create! row.to_hash
end
end
我的控制器:
def import
Distrib.import(params[:file])
redirect_to distribs_path, notice: "Contact imported."
end
我的观点:
<%= form_tag({action: :import}, multipart: true) do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
我设法创建了正确的记录,但它们都是空的。
puts(row.to_hash)
返回以下内容:
{"email;first_name;last_name;telephone;company;address;city;country;memo"=>"Etienny@yahoo.fr;Etienne;Ton;22142536475;HKM;456 Fifth Avenue;New York;US;Met at Uni"}
如何正确处理这些行以插入PostgreSQL数据库?
您代码的问题之一可能是CSV代表 *逗号分隔的值"文件",但是您有一个半分离器。尝试以下操作:
CSV.foreach(file.path, {headers: true, col_sep: ";"}) do |row|
puts(*attribute_names)
puts(row.to_hash)
...
end
这应该具有puts(row.to_hash)
的正确输出。