我有两个模型如下
Class Scheme < ActiveRecord::Base
has_many :navs, :foreign_key => :schemeCode, :primary_key => :schemeCode
end
Class Nav < ActiveRecord::Base
belongs_to :scheme, :foreign_key => :schemeCode, :primary_key => :schemeCode
end
两者都通过schemeCode连接,我需要向Nav模型插入数百万个导航,我正在使用大量插入,如下所示。
widgets.each do |record|
navs.push "('#{record["N1"]}','#{record["N3"]}','#{record["N4"].round(8)}')"
noOfRecords += 1
if(noOfRecords > 100000)
sql = "INSERT INTO navs (`schemeCode`, `navDate`, `navValue`) VALUES #{navs.join(", ")}"
ActiveRecord::Base.connection.execute sql
navs = []
noOfRecords = 1
end
end
小部件是来自DBF文件的数据。现在我只需要在方案表中存在特定的方案代码时才推送Nav。我想到了两种方法。
1)一个是在将导航推送到阵列进行大量插入之前检查Schemes表中的schemeCode可用性 - &gt;这是非常昂贵的,因为对于数百万条记录,它将查询数百万次。
2)在推送之前拉出阵列中的所有Schemecode并检查数组中的schemeCode是否存在,总共将是最大2K到3K的方案。 - &GT;我不确定它的性能,因为它需要迭代数组超过一百万次。
请以最好的方法帮助我处理这种情况。