From 1c9e6f6b1eadcc84c26396482a93cb68c1cae99a Mon Sep 17 00:00:00 2001 From: Jeremy Woertink Date: Thu, 3 Aug 2023 17:53:43 -0700 Subject: [PATCH] Fixing upsert so you can update a field to nil. Fixes #864 --- spec/avram/operations/save_operation_spec.cr | 18 ++++++++++++++++++ src/avram/upsert.cr | 4 ++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/spec/avram/operations/save_operation_spec.cr b/spec/avram/operations/save_operation_spec.cr index 0d5d235f2..d6dae2815 100644 --- a/spec/avram/operations/save_operation_spec.cr +++ b/spec/avram/operations/save_operation_spec.cr @@ -260,6 +260,17 @@ describe "Avram::SaveOperation" do user.joined_at.should eq(joined_at) end end + + it "allows updating nilable fields to nil" do + UserFactory.create(&.name("test").total_score(100)) + UpsertUserOperation.upsert(name: "test", total_score: nil) do |operation, updated_user| + operation.updated?.should eq(true) + updated_user.should_not eq(nil) + user = updated_user.as(User) + user.name.should eq("test") + user.total_score.should eq(nil) + end + end end describe ".upsert!" do @@ -307,6 +318,13 @@ describe "Avram::SaveOperation" do user.joined_at.should eq(joined_at) end + it "allows updating nilable fields to nil" do + UserFactory.create(&.name("test").total_score(100)) + user = UpsertUserOperation.upsert!(name: "test", total_score: nil) + user.name.should eq("test") + user.total_score.should eq(nil) + end + it "raises if the record is invalid" do expect_raises(Avram::InvalidOperationError) do UpsertUserOperation.upsert!(name: "") diff --git a/src/avram/upsert.cr b/src/avram/upsert.cr index 9d1ae5815..419eb8f01 100644 --- a/src/avram/upsert.cr +++ b/src/avram/upsert.cr @@ -63,7 +63,7 @@ module Avram::Upsert existing_record = find_existing_unique_record(operation) if existing_record - operation.record = existing_record + operation = new(existing_record, *args, **named_args) end operation.save! @@ -74,7 +74,7 @@ module Avram::Upsert existing_record = find_existing_unique_record(operation) if existing_record - operation.record = existing_record + operation = new(existing_record, *args, **named_args) end operation.save