我已经尝试了一段时间才找到合适的命令来做一个upsert,但我失败了。
以下是我正在尝试的内容:
csv.each do |row|
inner = {}
if row['PN'] != 'TOTAL'
time = Time.now
stamp = time.strftime("%F")
inner = {
'PN' => row['PN'],
'thisWkUse' => row['this WK Usage'], 'thisWkFail' => row['this WK Failure'], 'thisWkFailPercent' => row['this WK Failure%'].gsub('%',''),
'prev4WkUse' => row['Previous 4 WK Usage'], 'prev4WkFail' => row['Previous 4 WK Failure'], 'prev4WkFailPercent' => row['Previous 4 WK Failure%'].gsub('%',''),
'Platform' => row['Platform'].gsub('%',''),
'created' => stamp
}
@report = Report.find(PN: inner['PN'], Platform: inner['Platform']).update(inner,[upsert: true ])
@report.upsert()
end
end
以下是我看到的错误:
MOPED: someip:someport QUERY database=reidb collection=reports selector={"_id"=> {:PN=>"7056733", :Platform=>"CALLISTO_PLUS"}} flags=[] limit=0 skip=0 batch_size=nil fields=nil runtime: 92.2640ms
Completed 500 Internal Server Error in 447ms
NoMethodError (undefined method `upsert' for nil:NilClass):
app/controllers/reports_controller.rb:54:in `block in upload'
app/controllers/reports_controller.rb:42:in `upload'
以下是模型:
class Report
include Mongoid::Document
field :_id, type: Object
field :PN, type: String
field :thisWkUse, type: Integer
field :thisWkFail, type: Integer
field :thisWkFailPercent, type: Float
field :prev4WkUse, type: Integer
field :prev4WkFail, type: Integer
field :prev4WkFailPercent, type: Float
field :Platform, type: String
field :created, type: Date
index({ _id: 1,PN: 1, Platform: 1 }, { unique: true, background: true , drop_dups: true})
end
答案 0 :(得分:0)
上述一个衬垫都没有为我工作,所以我用丑陋的方式做到了:
inner = {
'PN' => row['PN'],
'thisWkUse' => row['this WK Usage'], 'thisWkFail' => row['this WK Failure'], 'thisWkFailPercent' => row['this WK Failure%'].gsub('%',''),
'prev4WkUse' => row['Previous 4 WK Usage'], 'prev4WkFail' => row['Previous 4 WK Failure'], 'prev4WkFailPercent' => row['Previous 4 WK Failure%'].gsub('%',''),
'Platform' => row['Platform'].gsub('%','')
}
@test = Report.where(:PN => inner['PN'], :Platform => inner['Platform']).count
if @test == 0
@reports = Report.new(inner)
@reports.save
elsif @test == 1
@reports = Report.where(:PN => inner['PN'], :Platform => inner['Platform']).update(inner)
else
limit = @test - 1
@nuke = Report.where(:PN => inner['PN'], :Platform => inner['Platform']).limit(limit).delete
@reports = Report.where(:PN => inner['PN'], :Platform => inner['Platform']).update(inner)
end