Permalink
Browse files

Fix polymorphic preloads on NOT NULL _type columns.

Defer to Association#klass instead of having a custom/duplicate code.
  • Loading branch information...
thedarkone committed Apr 3, 2014
1 parent 9310741 commit 53a5f36762c238d17ced0d8b26b4cce60e2cb51a
@@ -134,7 +134,7 @@ def preload_one(association)
def grouped_records(association)
Hash[
records_by_reflection(association).map do |reflection, records|
- [reflection, records.group_by { |record| association_klass(reflection, record) }]
+ [reflection, records.group_by { |record| record.association(association).klass }]
end
]
end
@@ -153,15 +153,6 @@ def records_by_reflection(association)
end
end
- def association_klass(reflection, record)
- if reflection.macro == :belongs_to && reflection.options[:polymorphic]
- klass = record.send(reflection.foreign_type)
- klass && klass.constantize
- else
- reflection.klass
- end
- end
-
def preloader_for(reflection)
case reflection.macro
when :has_many
@@ -234,6 +234,17 @@ def test_finding_with_includes_on_null_belongs_to_polymorphic_association
end
end
+ def test_finding_with_includes_on_empty_polymorphic_type_column
+ sponsor = sponsors(:moustache_club_sponsor_for_groucho)
+ sponsor.update!(sponsorable_type: '', sponsorable_id: nil) # sponsorable_type column might be declared NOT NULL
+ sponsor = assert_queries(1) do
+ assert_nothing_raised { Sponsor.all.merge!(:includes => :sponsorable).find(sponsor.id) }
+ end
+ assert_no_queries do
+ assert_equal nil, sponsor.sponsorable
+ end
+ end
+
def test_loading_from_an_association
posts = authors(:david).posts.merge(:includes => :comments, :order => "posts.id").to_a
assert_equal 2, posts.first.comments.size

0 comments on commit 53a5f36

Please sign in to comment.