Skip to content

Commit

Permalink
Fixes polymorphic joins.
Browse files Browse the repository at this point in the history
* Polymorphic joins have been missing a critical join constraint that
is responsible for only returning polymorphic records of the specified
type.

* Override ActiveRecord::Reflection::AbstractReflection#join_scope to
add this constraint if the reflection is polymorphic.
  • Loading branch information
PhilCoggins committed May 11, 2020
1 parent 90dd40d commit 387a71f
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
13 changes: 10 additions & 3 deletions lib/polyamorous/activerecord_5.2_ruby_2/reflection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,17 @@ module Polyamorous
module ReflectionExtensions
def build_join_constraint(table, foreign_table)
if polymorphic?
super(table, foreign_table)
.and(foreign_table[foreign_type].eq(klass.name))
super.and(foreign_table[foreign_type].eq(klass.name))
else
super(table, foreign_table)
super
end
end

def join_scope(table, foreign_table, foreign_klass)
if respond_to?(:polymorphic?) && polymorphic?
super.where!(foreign_table[foreign_type].eq(klass.name))
else
super
end
end
end
Expand Down
1 change: 1 addition & 0 deletions spec/ransack/search_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -328,6 +328,7 @@ module Ransack
s = Search.new(Note, notable_of_Person_type_name_eq: 'Ernie').result
expect(s).to be_an ActiveRecord::Relation
expect(s.to_sql).to match /#{people_name_field} = 'Ernie'/
expect(s.to_sql).to match /"notes"."notable_type" = 'Person'/
end

it 'evaluates nested conditions' do
Expand Down

0 comments on commit 387a71f

Please sign in to comment.