Skip to content

Commit

Permalink
Fix compile error when preloading optional associations (#925)
Browse files Browse the repository at this point in the history
  • Loading branch information
akadusei committed Jan 18, 2023
1 parent 6d5357e commit 81add34
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
10 changes: 10 additions & 0 deletions spec/avram/preloading/preloading_belongs_to_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -209,5 +209,15 @@ describe "Preloading belongs_to associations" do
comments[1].post.title.should eq("THIS IS CHANGED")
end
end

it "works for optional associations" do
with_lazy_load(enabled: false) do
business = BusinessFactory.new.create
email_address = EmailAddressFactory.create &.business_id(business.id)
email_address = EmailAddressQuery.preload_business(email_address)

email_address.business.try(&.id).should eq(business.id)
end
end
end
end
3 changes: 2 additions & 1 deletion src/avram/associations/belongs_to.cr
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,8 @@ module Avram::Associations::BelongsTo
return record if record._{{ assoc_name }}_preloaded? && !force

new_record = record.dup
assoc = preload_query.id(record.{{ foreign_key }}).first?
assoc = record.{{ foreign_key }}.try { |id| preload_query.id(id).first? }

new_record.__set_preloaded_{{ assoc_name }}(assoc)
new_record
end
Expand Down

0 comments on commit 81add34

Please sign in to comment.