Skip to content

Commit

Permalink
Fixing upsert so you can update a field to nil. Fixes #864 (#957)
Browse files Browse the repository at this point in the history
  • Loading branch information
jwoertink authored Aug 5, 2023
1 parent b3709c4 commit 77fcecf
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
18 changes: 18 additions & 0 deletions spec/avram/operations/save_operation_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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: "")
Expand Down
4 changes: 2 additions & 2 deletions src/avram/upsert.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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!
Expand All @@ -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
Expand Down

0 comments on commit 77fcecf

Please sign in to comment.