如何在导入前验证数据库中是否存在记录?

时间:2018-02-21 16:13:54

标签: sqlite ruby-on-rails-5

我有一个有效的导入功能。问题是如果记录已经在表中,则会创建副本。表中只有一个名为mtype的字段。所以CSV文件看起来像

mtype
HP360
Dell

正在运作的导入:

require 'csv'
class Modeltype < ApplicationRecord
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Modeltype.create! row.to_hash
    end
  end
end

我尝试搜索以查看记录是否在数据库中:

require 'csv'
class Modeltype < ApplicationRecord
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      tag = row.to_hash
      if Modeltype.find_by_mtype(tag) == nil
        Modeltype.create! row.to_hash
      end
    end
  end
end

当我像这样运行时,它返回一个&#34;无法转换哈希错误。&#34;

在控制器中我有:

def import
    Modeltype.import(params[:file])
    redirect_to modeltypes_url, notice: "Model Types imported."
end

如何搜索以查看记录是否已存在?然后创建它,如果它不存在,并跳过该行,如果它存在?我也尝试使用标志validates_presence_of,但这也没有用。

我似乎记得以前在不同的项目中使用validates_uniquness_of,这可能有用吗?

1 个答案:

答案 0 :(得分:2)

在你的modeltype.rb文件中,在你的def之外添加一行但是在Modeltype validates_uniqueness_of :mtype类中。如果项目不在数据库中,这将允许导入工作。如果在导入期间存在记录,您仍需要构建一个catch来跳过。否则你会收到错误。所以你添加了那条原始的def,就像这样:

require 'csv'
class Modeltype < ApplicationRecord
  validates_uniqueness_of :mtype
  def self.import(file)
    CSV.foreach(file.path, headers: true) do |row|
      Modeltype.create! row.to_hash
    end
  end
end