|
| 1 | +# frozen_string_literal: true |
| 2 | + |
1 | 3 | module Arel
|
2 | 4 | module ActiveRecordRelationExtension
|
3 |
| - def delete_all(conditions = nil) |
4 |
| - tenant_id = MultiTenant.current_tenant_id |
5 |
| - tenant_key = MultiTenant.partition_key(MultiTenant.current_tenant_class) |
| 5 | + # Overrides the delete_all method to include tenant scoping |
| 6 | + def delete_all |
| 7 | + # Call the original delete_all method if the current tenant is identified by an ID |
| 8 | + return super if MultiTenant.current_tenant_is_id? || MultiTenant.current_tenant.nil? |
6 | 9 |
|
| 10 | + tenant_key = MultiTenant.partition_key(MultiTenant.current_tenant_class) |
| 11 | + tenant_id = MultiTenant.current_tenant_id |
7 | 12 | arel = eager_loading? ? apply_join_dependency.arel : build_arel
|
8 | 13 | arel.source.left = table
|
9 | 14 |
|
10 |
| - group_values_arel_columns = arel_columns(group_values.uniq) |
11 |
| - having_clause_ast = having_clause.ast unless having_clause.empty? |
12 |
| - stmt = arel.compile_delete(table[primary_key], having_clause_ast, group_values_arel_columns) |
13 |
| - |
14 |
| - if tenant_id |
15 |
| - tenant_condition = table[tenant_key.downcase].eq(tenant_id) |
16 |
| - account_condition = table["account_id"].eq(tenant_id) |
17 |
| - conditions = Arel::Nodes::And.new([tenant_condition, conditions].compact) |
18 |
| - puts "conditions: #{conditions.to_sql}" |
19 |
| - puts "tenant_id: #{tenant_id}" |
| 15 | + if tenant_id && klass.column_names.include?(tenant_key) |
| 16 | + # Check if the tenant key is present in the model's column names |
| 17 | + tenant_condition = table[tenant_key].eq(tenant_id) |
| 18 | + # Add the tenant condition to the arel query if it is not already present |
| 19 | + unless arel.constraints.any? { |node| node.to_sql.include?(tenant_condition.to_sql) } |
| 20 | + arel = arel.where(tenant_condition) |
| 21 | + end |
20 | 22 | end
|
21 | 23 |
|
22 |
| - puts "stmt klass: #{stmt.class}" |
23 |
| - |
24 |
| - if conditions |
25 |
| - stmt.where(conditions) |
26 |
| - end |
| 24 | + subquery = arel.clone |
| 25 | + subquery.projections.clear |
| 26 | + subquery = subquery.project(table[primary_key]) |
| 27 | + in_condition = Arel::Nodes::In.new(table[primary_key], subquery.ast) |
| 28 | + stmt = Arel::DeleteManager.new.from(table) |
| 29 | + stmt.wheres = [in_condition] |
27 | 30 |
|
28 |
| - puts "stmtt: #{stmt.to_sql}" |
| 31 | + # Execute the delete statement using the connection and return the result |
29 | 32 | klass.connection.delete(stmt, "#{klass} Delete All").tap { reset }
|
30 | 33 | end
|
31 | 34 | end
|
|
0 commit comments