Skip to content

Commit d33e09c

Browse files
committed
feat(RelatableResource): extract sub query into constant
Extracts the shared polymorphic-reference subquery from RelatableResource into a constant so including classes can reuse it if they oeverride the .deletable scope, because you can't call super in scopes.
1 parent 6826968 commit d33e09c

1 file changed

Lines changed: 14 additions & 4 deletions

File tree

app/models/concerns/alchemy/relatable_resource.rb

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,19 @@ module Alchemy
22
module RelatableResource
33
extend ActiveSupport::Concern
44

5+
# SQL subquery selecting +related_object_id+ values for ingredients that
6+
# reference a given polymorphic type. Intended to be composed into a
7+
# +NOT IN (...)+ clause by +deletable+ and any overrides in including
8+
# classes. Takes one named bind :type - the polymorphic type name,
9+
# typically the class name of the including model
10+
# (e.g. +"Alchemy::Attachment"+).
11+
RELATED_INGREDIENTS_SUBQUERY = <<~SQL.squish
12+
SELECT related_object_id
13+
FROM alchemy_ingredients
14+
WHERE related_object_id IS NOT NULL
15+
AND related_object_type = :type
16+
SQL
17+
518
class_methods do
619
# Preload associations for element editor display
720
#
@@ -18,10 +31,7 @@ def alchemy_element_preloads(records)
1831

1932
included do
2033
scope :deletable, -> do
21-
where(
22-
"#{table_name}.id NOT IN (SELECT related_object_id FROM alchemy_ingredients WHERE related_object_id IS NOT NULL AND related_object_type = ?)",
23-
name
24-
)
34+
where("#{table_name}.id NOT IN (#{RELATED_INGREDIENTS_SUBQUERY})", type: name)
2535
end
2636

2737
has_many :related_ingredients,

0 commit comments

Comments
 (0)