|
| 1 | +module PolymorphicIntegerType |
| 2 | + module PredicateBuilderExtension |
| 3 | + |
| 4 | + # Original Code: |
| 5 | + # def self.expand(klass, table, column, value) |
| 6 | + # queries = [] |
| 7 | + |
| 8 | + # # Find the foreign key when using queries such as: |
| 9 | + # # Post.where(author: author) |
| 10 | + # # |
| 11 | + # # For polymorphic relationships, find the foreign key and type: |
| 12 | + # # PriceEstimate.where(estimate_of: treasure) |
| 13 | + # if klass && reflection = klass._reflect_on_association(column) |
| 14 | + # base_class = polymorphic_base_class_from_value(value) |
| 15 | + |
| 16 | + # if reflection.polymorphic? && base_class |
| 17 | + # queries << build(table[reflection.foreign_type], base_class) |
| 18 | + # end |
| 19 | + |
| 20 | + # column = reflection.foreign_key |
| 21 | + |
| 22 | + # if base_class |
| 23 | + # primary_key = reflection.association_primary_key(base_class) |
| 24 | + # value = convert_value_to_association_ids(value, primary_key) |
| 25 | + # end |
| 26 | + # end |
| 27 | + |
| 28 | + # queries << build(table[column], value) |
| 29 | + # queries |
| 30 | + # end |
| 31 | + |
| 32 | + def expand(klass, table, column, value) |
| 33 | + queries = [] |
| 34 | + |
| 35 | + # Find the foreign key when using queries such as: |
| 36 | + # Post.where(author: author) |
| 37 | + # |
| 38 | + # For polymorphic relationships, find the foreign key and type: |
| 39 | + # PriceEstimate.where(estimate_of: treasure) |
| 40 | + if klass && reflection = klass._reflect_on_association(column) |
| 41 | + base_class = polymorphic_base_class_from_value(value) |
| 42 | + |
| 43 | + if reflection.polymorphic? && base_class |
| 44 | + if klass.respond_to?("#{column}_type_mapping") |
| 45 | + queries << build(table[reflection.foreign_type], klass.send("#{column}_type_mapping").key(base_class.to_s)) |
| 46 | + else |
| 47 | + queries << build(table[reflection.foreign_type], base_class) |
| 48 | + end |
| 49 | + end |
| 50 | + |
| 51 | + column = reflection.foreign_key |
| 52 | + |
| 53 | + if base_class |
| 54 | + primary_key = reflection.association_primary_key(base_class) |
| 55 | + value = convert_value_to_association_ids(value, primary_key) |
| 56 | + end |
| 57 | + end |
| 58 | + |
| 59 | + queries << build(table[column], value) |
| 60 | + queries |
| 61 | + end |
| 62 | + end |
| 63 | +end |
| 64 | + |
| 65 | +ActiveRecord::PredicateBuilder.singleton_class.prepend(PolymorphicIntegerType::PredicateBuilderExtension) |
0 commit comments