Revert 39468944 and fix osmlab#91 without loosing the editor choice
[rails.git] / config / initializers / composite_primary_keys.rb
1 # Monkey patch composite_primary_keys pending the resolution of:
2 # https://github.com/composite-primary-keys/composite_primary_keys/pull/170
3 module ActiveRecord
4   module Associations
5     class HasManyAssociation
6       def delete_records(records, method)
7         if method == :destroy
8           records.each { |r| r.destroy }
9           update_counter(-records.length) unless inverse_updates_counter_cache?
10         else
11           if records == :all
12             scope = self.scope
13           else
14             # CPK
15             # keys  = records.map { |r| r[reflection.association_primary_key] }
16             # scope = scope.where(reflection.association_primary_key => keys)
17             table = Arel::Table.new(reflection.table_name)
18             and_conditions = records.map do |record|
19               eq_conditions = Array(reflection.association_primary_key).map do |name|
20                 table[name].eq(record[name])
21               end
22               Arel::Nodes::And.new(eq_conditions)
23             end
24
25             condition = and_conditions.shift
26             and_conditions.each do |and_condition|
27               condition = condition.or(and_condition)
28             end
29
30             scope = self.scope.where(condition)
31           end
32
33           if method == :delete_all
34             update_counter(-scope.delete_all)
35           else
36             # CPK
37             # update_counter(-scope.update_all(reflection.foreign_key => nil))
38             updates = Array(reflection.foreign_key).inject(Hash.new) do |hash, name|
39               hash[name] = nil
40               hash
41             end
42             update_counter(-scope.update_all(updates))
43           end
44         end
45       end
46     end
47   end
48 end