Skip to content

Commit

Permalink
If there's a blueprint that renders itself, halt after one level.
Browse files Browse the repository at this point in the history
  • Loading branch information
jhollinger committed Jun 12, 2024
1 parent cdbb7f5 commit 03f5f48
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 2 deletions.
9 changes: 7 additions & 2 deletions lib/blueprinter-activerecord/preloader.rb
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,13 @@ def self.preloads(blueprint, view_name, model=nil)
# look for a matching association on the model
ref = model ? model.reflections[assoc.name.to_s] : nil
if (ref || model.nil?) && !assoc.blueprint.is_a?(Proc)
ref_model = ref && !(ref.belongs_to? && ref.polymorphic?) ? ref.klass : nil
acc[assoc.name] = preloads(assoc.blueprint, assoc.view, ref_model)
acc[assoc.name] =
if assoc.blueprint == blueprint and assoc.view == view_name
{} # halt on recursive blueprints
else
ref_model = ref && !(ref.belongs_to? && ref.polymorphic?) ? ref.klass : nil
preloads(assoc.blueprint, assoc.view, ref_model)
end
end

# look for a :preload option on the association
Expand Down
9 changes: 9 additions & 0 deletions test/preloads_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,13 @@ def test_preload_with_annotated_associations
battery1: {refurb_plan: {}},
}, preloads)
end

def test_preload_with_recursive_association
blueprint = Class.new(Blueprinter::Base) do
association :children, blueprint: self
end

preloads = BlueprinterActiveRecord::Preloader.preloads(blueprint, :default, Category)
assert_equal({children: {}}, preloads)
end
end
2 changes: 2 additions & 0 deletions test/support/active_record_models.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Project < ActiveRecord::Base

class Category < ActiveRecord::Base
belongs_to :company
belongs_to :parent, class_name: "Category", optional: true
has_many :children, foreign_key: :parent_id, class_name: "Category", inverse_of: :parent
end

class Widget < ActiveRecord::Base
Expand Down
1 change: 1 addition & 0 deletions test/support/active_record_schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ def self.load!

create_table :categories do |t|
t.string :name, null: false
t.integer :parent_id
t.text :description
end

Expand Down

0 comments on commit 03f5f48

Please sign in to comment.