Skip to content

Commit

Permalink
Adding block override for preloading with has_one. Fixes #985 (#994)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink authored Dec 29, 2023
1 parent 82eef3e commit 49f6ccb
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
11 changes: 11 additions & 0 deletions spec/avram/preloading/preloading_has_many_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,17 @@ describe "Preloading has_many associations" do
end
end

it "works with blocks" do
with_lazy_load(enabled: false) do
post = PostFactory.create
comment = CommentFactory.create &.post_id(post.id)

posts = Post::BaseQuery.new.preload_comments(&.id.not.eq(comment.id))

posts.results.first.comments.should eq([] of Comment)
end
end

it "works with UUID foreign keys" do
with_lazy_load(enabled: false) do
item = LineItemFactory.create
Expand Down
12 changes: 12 additions & 0 deletions spec/avram/preloading/preloading_has_one_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,18 @@ describe "Preloading has_one associations" do
end
end

it "works with a block" do
with_lazy_load(enabled: false) do
admin = AdminFactory.create
sign_in_credential = SignInCredentialFactory.create &.user_id(admin.id)

admin = Admin::BaseQuery.new.preload_sign_in_credential(&.user_id(admin.id))

admin.first.sign_in_credential_preloaded?.should eq(true)
admin.first.sign_in_credential.should eq sign_in_credential
end
end

it "works with optional association" do
with_lazy_load(enabled: false) do
UserFactory.create
Expand Down
5 changes: 5 additions & 0 deletions src/avram/associations/has_one.cr
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,11 @@ module Avram::Associations::HasOne
preload_{{ assoc_name }}({{ model }}::BaseQuery.new)
end

def preload_{{ assoc_name }} : self
modified_query = yield {{ model }}::BaseQuery.new
preload_{{ assoc_name }}(modified_query)
end

def preload_{{ assoc_name }}(preload_query : {{ model }}::BaseQuery) : self
add_preload do |records|
ids = records.map(&.id)
Expand Down

0 comments on commit 49f6ccb

Please sign in to comment.