Skip to content

Commit

Permalink
Create class to map join table and simplify code
Browse files Browse the repository at this point in the history
  • Loading branch information
Matt-Yorkley committed Jan 27, 2021
1 parent aed912a commit c30e018
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 30 deletions.
8 changes: 8 additions & 0 deletions app/models/spree/option_values_line_item.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# frozen_string_literal: true

module Spree
class OptionValuesLineItem < ActiveRecord::Base
belongs_to :line_item, class_name: 'Spree::LineItem'
belongs_to :option_value, class_name: 'Spree::OptionValue'
end
end
15 changes: 2 additions & 13 deletions lib/tasks/data/remove_transient_data.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ def call
Session.where("updated_at < ?", SHORT_RETENTION).delete_all

clear_old_cart_data!
clear_line_item_option_values!
end

private
Expand All @@ -29,25 +28,15 @@ def clear_old_cart_data!
merge(orders_without_payments)

old_cart_line_items = Spree::LineItem.where(order_id: old_carts)
old_line_item_options = Spree::OptionValuesLineItem.where(line_item_id: old_cart_line_items)
old_cart_adjustments = Spree::Adjustment.where(order_id: old_carts)

old_cart_adjustments.delete_all
old_line_item_options.delete_all
old_cart_line_items.delete_all
old_carts.delete_all
end

def clear_line_item_option_values!
ActiveRecord::Base.connection.execute <<-SQL
DELETE FROM spree_option_values_line_items
WHERE line_item_id IN (
SELECT line_item_id FROM spree_option_values_line_items
LEFT OUTER JOIN spree_line_items
ON spree_option_values_line_items.line_item_id = spree_line_items.id
WHERE spree_line_items.id IS NULL
);
SQL
end

def orders_without_payments
# Carts with failed payments are ignored, as they contain potentially useful data
Spree::Order.
Expand Down
22 changes: 5 additions & 17 deletions spec/lib/tasks/data/remove_transient_data_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,23 +61,11 @@
expect{ old_adjustment.reload }.to raise_error ActiveRecord::RecordNotFound
end

context "removing defunct line item option value records" do
let(:connection) { ActiveRecord::Base.connection }
let(:query) {
<<-SQL
SELECT * FROM spree_option_values_line_items
LEFT OUTER JOIN spree_line_items
ON spree_option_values_line_items.line_item_id = spree_line_items.id
WHERE spree_line_items.id IS NULL;
SQL
}

it "removes the records" do
line_item.delete

expect{ RemoveTransientData.new.call }.
to change{ connection.execute(query).count }.by(-1)
end
it "removes any defunct line item option value records" do
line_item.delete

expect{ RemoveTransientData.new.call }.
to change{ Spree::OptionValuesLineItem.count }.by(-1)
end
end
end
Expand Down

0 comments on commit c30e018

Please sign in to comment.