Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding block override for preloading with has_one. #994

Merged
merged 1 commit into from
Dec 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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