Skip to content

Commit 38d0343

Browse files
author
Kyle d'Oliveira
committed
Merge branch 'rails4-extension-for-direct-associations-queries' of github.com:/rubeard/polymorphic_integer_type into rails4-support
2 parents 20c19c5 + c466a1e commit 38d0343

4 files changed

Lines changed: 47 additions & 2 deletions

File tree

lib/polymorphic_integer_type.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
require "polymorphic_integer_type/version"
22
require "polymorphic_integer_type/extensions"
33
require "polymorphic_integer_type/mapping"
4-
require "polymorphic_integer_type/polymorphic_array_value_extension"
4+
if Gem::Version.new(ActiveRecord::VERSION::STRING) < Gem::Version.new("5")
5+
require "polymorphic_integer_type/predicate_builder_extension"
6+
else
7+
require "polymorphic_integer_type/polymorphic_array_value_extension"
8+
end
59

610
module PolymorphicIntegerType; end

lib/polymorphic_integer_type/extensions.rb

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@ def belongs_to(name, scope = nil, **options)
2424
mapping
2525
end
2626

27+
# Required way to dynamically define a class method on the model
28+
singleton_class.__send__(:define_method, "#{foreign_type}_mapping") do
29+
mapping
30+
end
31+
2732
define_method foreign_type do
2833
t = super()
2934
mapping[t]
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module PolymorphicIntegerType
2+
module PredicateBuilderExtension
3+
def expand(klass, table, column, value)
4+
queries = []
5+
6+
# Find the foreign key when using queries such as:
7+
# Post.where(author: author)
8+
#
9+
# For polymorphic relationships, find the foreign key and type:
10+
# PriceEstimate.where(estimate_of: treasure)
11+
if klass && reflection = klass._reflect_on_association(column)
12+
base_class = polymorphic_base_class_from_value(value)
13+
14+
if reflection.polymorphic? && base_class
15+
if klass.respond_to?("#{column}_type_mapping")
16+
queries << build(table[reflection.foreign_type], klass.send("#{column}_type_mapping").key(base_class.to_s))
17+
else
18+
queries << build(table[reflection.foreign_type], base_class)
19+
end
20+
end
21+
22+
column = reflection.foreign_key
23+
24+
if base_class
25+
primary_key = reflection.association_primary_key(base_class)
26+
value = convert_value_to_association_ids(value, primary_key)
27+
end
28+
end
29+
30+
queries << build(table[column], value)
31+
queries
32+
end
33+
end
34+
end
35+
36+
ActiveRecord::PredicateBuilder.singleton_class.prepend(PolymorphicIntegerType::PredicateBuilderExtension)
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
module PolymorphicIntegerType
2-
VERSION = "2.2.0"
2+
VERSION = "2.2.1"
33
end

0 commit comments

Comments
 (0)