Ruby导入csv时跳过现有的logging

我的问题是,我必须导出一个Excel表格保存一些行到数据库没有重复或冗余,所以我开始导入CSV而不是XLS,然后当我完成我可能能够parsingxls这是我的模型代码:

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 

在machines_controller中导入方法

  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 

任何想法如何从保存到数据库跳过重复logging将不胜感激

唯一标识符:为了避免重复的logging保存到数据库,您应该维护除主键以外的唯一标识符。 这可以帮助您确定数据库中是否有可用的logging,如果可用,您可以从保存中跳过该logging。

我想你可以在这种情况下使用名称,这应该是唯一的数据库中的每个logging。 在模型中写一个唯一性validation来实现这一点。

更改后:

  validates_uniqueness_of :name def self.assign_row(row) a, b, c, d = row @c = c.slice(1,4) machine = Machine.find_by(name: c) Machine.create(name: c, mid: @c) if machine.blank? end 

希望能帮助到你!! 谢谢。