0
我的問題是,我必須導出一個Excel表格,將一些行保存到數據庫中,而不會有重複或冗餘 所以我開始導入CSV而不是XLS,然後當我完成時,我可能會解析XLS 這是我的模型代碼:在machines_controllerRuby導入csv時跳過現有記錄
require 'csv'
class Machine < ActiveRecord::Base
def self.assign_row(row)
a, b, c, d = row
@c = c.slice(1,4)
Machine.create(name: c, mid: @c)
end
def self.import(file)
CSV.foreach(file.path) do |row|
machine = Machine.assign_row(row)
end
end
end
導入方法
def import
count = Machine.import params[:file]
redirect_to machines_path, notice: "file imported successfully!"
end
遷移代碼
條def change
create_table :machines do |t|
t.string :name
t.string :mid
t.timestamps null: false
end
add_index :machines, :name, :unique => true
end
和視圖代碼
<%= form_tag import_machines_path, multipart: true do %>
<%= file_field_tag :file %>
<%= submit_tag "upload" %>
<% end %>
路線
Rails.application.routes.draw do
resources :errors
resources :machines do
collection do
post :import
end
end
root "machines#index
end
如何從保存到數據庫中跳過重複記錄的任何想法,將不勝感激 感謝
感謝您迴應 我這樣做,但我得到了MachinesController#進口 未定義的方法'進口」這個錯誤 NoMethodError爲#<類別:0x007fcb7c171638> – Amr
你可以更新路由你的問題? – harika
完成更新路線。 – Amr