Skip to content

Commit

Permalink
Load correct has_one association with lazy loading (#581)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewmcgarvey authored Dec 29, 2020
1 parent 8086287 commit 3ff7b13
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
3 changes: 3 additions & 0 deletions spec/lazy_loading_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ describe "Lazy loading associations" do
end

it "can lazy load has_one" do
# to verify it is loading the correct association, not just the first
SignInCredentialBox.new.user_id(AdminBox.create.id).create

admin = AdminBox.create
sign_in_credential = SignInCredentialBox.new.user_id(admin.id).create
admin.sign_in_credential!.should eq(sign_in_credential)
Expand Down
7 changes: 3 additions & 4 deletions src/avram/associations/has_one.cr
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,9 @@ module Avram::Associations::HasOne
if _{{ assoc_name }}_preloaded?
@_preloaded_{{ assoc_name }}{% unless nilable %}.not_nil!{% end %}
elsif lazy_load_enabled? || allow_lazy
query = {{ model }}::BaseQuery.new
query.{{ foreign_key.id }}(id)

query.first{% if nilable %}?{% end %}
{{ model }}::BaseQuery.new
.{{ foreign_key.id }}(id)
.first{% if nilable %}?{% end %}
else
raise Avram::LazyLoadError.new {{ @type.name.stringify }}, {{ assoc_name.stringify }}
end
Expand Down

0 comments on commit 3ff7b13

Please sign in to comment.