Skip to content

Commit 5c05c4b

Browse files
committed
fix(Page): Only ensure_draft_version for new records
Skip the callback entirely for persisted records. New records still get their draft_version built, while persisted records can use preloading or lazy loading. This fixes an issue with the preloaded page tree where the after_initialize callback was triggering individual queries for each page's draft_version during bulk loading, before Rails could apply preloading.
1 parent 770ee2d commit 5c05c4b

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

app/models/alchemy/page.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ class Page < BaseRecord
140140
validates_format_of :page_layout, with: /\A[a-z0-9_-]+\z/, unless: -> { page_layout.blank? }
141141
validates_presence_of :parent, unless: -> { layoutpage? || language_root? }
142142

143-
after_initialize :ensure_draft_version
143+
after_initialize :ensure_draft_version, if: :new_record?
144144

145145
before_save :set_language_code,
146146
if: -> { language.present? }

spec/models/alchemy/page_spec.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,24 @@ module Alchemy
135135
expect(page.draft_version.meta_description).to eq("Test")
136136
end
137137
end
138+
139+
context "for persisted pages" do
140+
let!(:persisted_page) do
141+
create(:alchemy_page, language: language, parent: language_root)
142+
end
143+
144+
let(:page) do
145+
Alchemy::Page.find(persisted_page.id)
146+
end
147+
148+
it "does not load draft_version association" do
149+
expect(page.association(:draft_version)).not_to be_loaded
150+
end
151+
152+
it "still provides draft_version when accessed" do
153+
expect(page.draft_version).to be_present
154+
end
155+
end
138156
end
139157

140158
context "before_save" do

0 commit comments

Comments
 (0)