Last active
June 20, 2018 19:20
-
-
Save dhruvasagar/5645b4c26db577a619bba0d6649e0639 to your computer and use it in GitHub Desktop.
Script to add master variants for spree_products that are missing them
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
puts "Rails environment is #{Rails.env}" | |
products_without_master = Spree::Product.joins('left outer join spree_variants sv on sv.product_id = spree_products.id and sv.is_master = 1').where('sv.id is null').all | |
ids_without_master = products_without_master.map(&:id) | |
puts "Spree products without master variants are #{ids_without_master.count} in number and have ids #{ids_without_master}" | |
updated_at_values = products_without_master.map(&:updated_at) | |
ActiveRecord::Base.transaction do | |
puts "Creating missing master variants inside a transaction..." | |
products_without_master.each do |sp| | |
updated_at = sp.updated_at | |
Spree::Variant.create!(product_id: id, is_master: true, cost_price: sp.teni_product.transfer_price) | |
sp.update_column(:updated_at, updated_at) | |
end | |
new_updated_at_values = Spree::Product.where(id: ids_without_master).pluck(:updated_at) | |
if updated_at_values == new_updated_at_values | |
puts "Congrats, updated_at values were preserved" | |
else | |
puts "Ugh, updated_at values were not preserved. See the differences yourself. Updated_at originally was #{updated_at_values}" | |
puts "Now, it is #{new_updated_at_values}" | |
puts "Cancelling transcation because of this. Bad luck." | |
end | |
puts "Now ids without master = #{ids_without_master}" | |
# raise "Need to cancel transaction -- just testing" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment