Skip to content

Instantly share code, notes, and snippets.

@dhruvasagar
Last active June 20, 2018 19:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dhruvasagar/5645b4c26db577a619bba0d6649e0639 to your computer and use it in GitHub Desktop.
Save dhruvasagar/5645b4c26db577a619bba0d6649e0639 to your computer and use it in GitHub Desktop.
Script to add master variants for spree_products that are missing them
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