我有一个有效的导入器功能。问题是如果记录已经在表中,它将创建一个重复项。表中只有一个字段称为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
当我像这样运行它时,它返回“无法转换哈希错误”。
在控制器中,我有:
def import
Modeltype.import(params[:file])
redirect_to modeltypes_url, notice: "Model Types imported."
end
如何搜索以查看记录是否已存在?然后创建它(如果不存在),并跳过该行(如果存在)?我也尝试使用标志validates_presence_of,但这也不起作用。
我似乎记得在其他项目上使用validates_uniquness_of,这可能有用吗?
在您的modeltype.rb文件中,在def之外的Modeltype类中添加该行validates_uniqueness_of :mtype
。如果该项目不在数据库中,这将使导入工作。如果记录在导入过程中存在,则您仍将需要构建捕获以跳过。否则,您将得到一个错误。因此添加了该行的原始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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句