Skip to content

Commit 5c558e4

Browse files
committed
Handle nil :uses through a polymorphic
When you `includes(:polymorphic => :attr)` and the `:attr` does not have a `:uses`, this threw an exception. Reason: Rails 7.2 added a `to_sym` in `reflect_on_association()`, since `uses[:attr] = nil`, calling `reflect_on_association(nil)` had issues: ``` Failure/Error: reflection = record.class._reflect_on_association(association) NoMethodError: undefined method `to_sym' for nil # /Users/kbrock/.gem/ruby/3.3.5/gems/activerecord-7.2.2.1/lib/active_record/reflection.rb:127:in `_reflect_on_association' # ./lib/active_record/virtual_attributes/virtual_fields.rb:189:in `block in grouped_records' ``` refs: - rails/rails#5172 - ManageIQ/manageiq-api#1284 Fixes: ManageIQ/manageiq#23518
1 parent d6a3c90 commit 5c558e4

File tree

3 files changed

+14
-0
lines changed

3 files changed

+14
-0
lines changed

lib/active_record/virtual_attributes/virtual_fields.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,7 @@ def grouped_records
183183
source_records.each do |record|
184184
# begin virtual_attributes changes
185185
association = record.class.replace_virtual_fields(self.association)
186+
next if association.nil?
186187
# end virtual_attributes changes
187188

188189
reflection = record.class._reflect_on_association(association)

spec/db/models.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,12 @@ def book_with_most_bookmarks
115115
# vs a more condensed format: {:bwmb => {}, :books => co_a}
116116
virtual_has_many :famous_co_authors, :uses => [:book_with_most_bookmarks, {:books => :co_authors}]
117117

118+
virtual_has_many :thoughts
119+
120+
def thoughts
121+
["one", "two"]
122+
end
123+
118124
def self.create_with_books(count)
119125
create!(:name => "foo", :blurb => "blah blah blah").tap { |author| author.create_books(count) }
120126
end

spec/virtual_includes_spec.rb

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,13 @@
106106
it "counts" do
107107
expect { expect(Author.includes(:books => :author_name).count).to eq(1) }.not_to raise_error
108108
end
109+
110+
# we are trying to get the includes with a nil uses to blow things up
111+
it "preloads through polymorphic to an association without a uses" do
112+
author = Author.first
113+
photo = author.photos.create
114+
expect(author.photos.includes(:imageable => :thoughts).first).to eq(photo)
115+
end
109116
end
110117

111118
# references follow a different path than just includes

0 commit comments

Comments
 (0)