如何,此代码具有以下结果:
# NOW
# there is 0 new record after running new_data array
# there is 0 changed record(s) after running new_data array
# there is 3 persisted record(s) after running new_data array
尝试得出以下结果:
# WANT
#there is 1 new record(s) after running new_data array
#there is 1 changed record(s) after running new_data array
#there is 2 persisted record(s) after running new_data array
*问题是:*
怎么做?。要记录更改和新记录的数量。
Cars.delete_all
original_data = [
{:brand => 'Mercedes', :used => false, :year => 2000 },
{:brand => 'Honda', :used => true , :year => 2000 },
{:brand => 'Nissan', :used => false, :year => 2000 }
]
new_data = [
# updating year to 2013
{:brand => 'Mercedes', :used => false, :year => 2013 },
# new record
{:brand => 'Tesla', :used => false, :year => 2013 },
# same data
{:brand => 'Nissan', :used => false, :year => 2000 }
]
# create new cars
original_data.each do |c|
Cars.create(c)
end
# updates
persisted = 0
new_records = 0
changed_records = 0
new_data.each do |c|
car = Cars.where(:brand => c[:brand]).first_or_create
persisted +=1 if car.persisted?
new_records +=1 if car.new_record?
changed_records +=1 if car.changed?
end
puts "there is #{new_records} new record(s) after running new_data array"
puts "there is #{changed_records} changed record(s) after running new_data array"
puts "there is #{persisted} persisted record(s) after running new_data array"
*更新*
根据答案的代码:-尝试仅更改1条记录,而不是2条。
# updates
persisted = 0
new_records = 0
changed_records = 0
new_data.each do |c|
car = Cars.where(:brand => c[:brand]).first_or_initialize
car.assign_attributes(c)
persisted +=1 if car.persisted?
new_records +=1 if car.new_record?
changed_records +=1 if car.changed?
car.save
end
there is 1 new record(s) after running new_data array
there is 2 changed record(s) after running new_data array
there is 2 persisted record(s) after running new_data array
您可以尝试first_or_initialize沿assign_attributes
new_data.each do |c|
car = Cars.where(:brand => c[:brand]).first_or_initialize
new_records +=1 if car.new_record?
car.save # first save the initialized AR
car.assign_attributes(c)
changed_records +=1 if car.changed?
car.save
end
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句