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

Fixing upsert so you can update a field to nil. #957

Merged
merged 1 commit into from
Aug 5, 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
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
Loading