【发布时间】:2014-11-01 13:46:02
【问题描述】:
我在这里遇到了障碍,需要帮助。我希望能够将 csv 文件导入我的 Active Record。使用 SmarterCSV 或其他方式
这是我的数据库
create_table "ques", force: true do |t|
t.integer "rikt_nr"
t.integer "start_nr"
t.integer "end_nr"
t.datetime "created_at"
t.datetime "updated_at"
end
这是我的看法
<h2>Import Ques</h2>
<%= form_tag import_ques_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "Import" %>
<% end %>
这是我的路线
resources :ques do
collection { post :import }
end
root to: 'ques#index'
和我的控制器
def import
Que.import(params[:file])
redirect_to root_url, notice: "Ques imported."
end
和模型
def self.import(file)
CSV.foreach(file.path, headers: true) do |row|
Que.create! row.to_hash
end
end
csv 文件看起来像这样
Id;Rikt nr;Start nr;End nr;Created at;Updated at
1;8;4486550;4486650;October 28, 2014 08:42;October 28, 2014 08:42
2;8;4486700;4486755;October 28, 2014 08:42;October 28, 2014 08:42
我查看了各种指南,但我无法让它发挥作用。
【问题讨论】:
-
你在哪里表示你的分隔符是分号而不是逗号?
-
Dosent smartercsv 修复该问题?
-
对不起,我复制了太多你的代码。跳过
.to_hash。我更新了我的答案。
标签: ruby-on-rails csv import rails-activerecord smartercsv