Skip to content

Commit 1d6044f

Browse files
committed
Classifications: Add foreign keys
This join table needs both references to be pointing to valid records. A uniqueness index for the taxon id in this table is already present.
1 parent 0648f0f commit 1d6044f

File tree

2 files changed

+34
-2
lines changed

2 files changed

+34
-2
lines changed

core/app/models/spree/classification.rb

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ module Spree
44
class Classification < Spree::Base
55
self.table_name = 'spree_products_taxons'
66
acts_as_list scope: :taxon
7-
belongs_to :product, class_name: "Spree::Product", inverse_of: :classifications, touch: true, optional: true
8-
belongs_to :taxon, class_name: "Spree::Taxon", inverse_of: :classifications, touch: true, optional: true
7+
belongs_to :product, class_name: "Spree::Product", inverse_of: :classifications, touch: true
8+
belongs_to :taxon, class_name: "Spree::Taxon", inverse_of: :classifications, touch: true
99

1010
# For https://github.com/spree/spree/issues/3494
1111
validates :taxon_id, uniqueness: { scope: :product_id, message: :already_linked }
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# frozen_string_literal: true
2+
3+
class AddFkToClassifications < ActiveRecord::Migration[7.0]
4+
def up
5+
# Uncomment the following code to remove orphaned records if this migration fails
6+
#
7+
# say_with_time "Removing orphaned orders (no corresponding user)" do
8+
# Spree::Classification.left_joins(:product).where(spree_products: { id: nil }).delete_all
9+
# Spree::Classification.left_joins(:taxon).where(spree_taxons: { id: nil }).delete_all
10+
# end
11+
12+
add_foreign_key :spree_products_taxons, :spree_products, column: :product_id
13+
add_foreign_key :spree_products_taxons, :spree_taxons, column: :taxon_id
14+
rescue ActiveRecord::StatementInvalid => e
15+
if e.cause.is_a?(PG::ForeignKeyViolation) || e.cause.is_a?(Mysql2::Error) || e.cause.is_a?(SQLite3::ConstraintException)
16+
Rails.logger.warn <<~MSG
17+
⚠️ Foreign key constraint failed when adding :spree_products_taxons => :spree_products.
18+
⚠️ Foreign key constraint failed when adding :spree_products_taxons => :spree_taxons.
19+
To fix this:
20+
1. Uncomment the code that removes orphaned records.
21+
2. Rerun the migration.
22+
Offending error: #{e.cause.class} - #{e.cause.message}
23+
MSG
24+
end
25+
raise
26+
end
27+
28+
def down
29+
remove_foreign_key :spree_products_taxons, :spree_products, column: :product_id
30+
remove_foreign_key :spree_products_taxons, :spree_taxons, column: :taxon_id
31+
end
32+
end

0 commit comments

Comments
 (0)