class AddLineItemIdToSpreeInventoryUnits < ActiveRecord::Migration
  def change
    # Stores running the product-assembly extension already have a line_item_id column
    unless column_exists? Spree::InventoryUnit.table_name, :line_item_id
      add_column :spree_inventory_units, :line_item_id, :integer
      add_index :spree_inventory_units, :line_item_id

      Spree::Shipment.includes(:inventory_units, :order).find_each do |shipment|
        shipment.inventory_units.group_by(&:variant).each do |variant, units|

          line_item = shipment.order.find_line_item_by_variant(variant)
          next unless line_item

          Spree::InventoryUnit.where(id: units.map(&:id)).update_all(line_item_id: line_item.id)
        end
      end
    end
  end
end

class AddLineItemIdToSpreeInventoryUnits < ActiveRecord::Migration
  def change
    # Stores running the product-assembly extension already have a line_item_id column
    unless column_exists? Spree::InventoryUnit.table_name, :line_item_id
      add_column :spree_inventory_units, :line_item_id, :integer
      add_index :spree_inventory_units, :line_item_id

      shipments = Spree::Shipment.includes(:inventory_units, :order)

      shipments.find_each do |shipment|
        shipment.inventory_units.group_by(&:variant_id).each do |variant, units|

          line_item = shipment.order.line_items.find_by(variant_id: variant_id)
          next unless line_item

          Spree::InventoryUnit.where(id: units.map(&:id)).update_all(line_item_id: line_item.id)
        end
      end
    end
  end
end

Make migration more tolerant of deleted Variants
Make migration more tolerant of deleted Variants

This migration bailed for me when it found an old order (before Spree used `acts_as_paranoid`) with a line_item referencing a Variant that no longer existed.

Making the migration use `variant_id` instead of `variant.id` fixed this problem for me, and I suspect will make the migration path smoother for other people who have been using Spree since before the `paranoia` gem.

Fixes #4822
