Skip to content

Conversation

@treagod
Copy link
Contributor

@treagod treagod commented Feb 2, 2026

This commit adds a new #update_or_create method to the querysets.

With this newly added method a developer can update specific fields, defined by updates, of record that matches the filter or, if no record can be found, create a new record. The new record will either created by the updates arguments or a custom defaults hash can be used if creation requires certain fields to be set

Closes #308

@treagod treagod marked this pull request as draft February 2, 2026 11:51
@treagod treagod marked this pull request as ready for review February 5, 2026 12:43
@treagod treagod requested a review from ellmetha February 6, 2026 17:24
)
record = get!(Node.new(**kwargs))
record.set_field_values(updates)
record.save(using: @query.using)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess it could be interesting to have an #update_or_create! variant of the method where we call #save! so that an exception is raised if the created/updated record is invalid.

record.save(using: @query.using)
record
rescue Errors::RecordNotFound
update_attributes = defaults.nil? ? updates : defaults.not_nil!
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we be using both the updates AND defaults values here if defaults is set? Technically, the method should create new records with defaults if they do not exist yet, but all the records should end up having the updates values after the method is called (regardless of whether they got created/updated).

Suggested change
update_attributes = defaults.nil? ? updates : defaults.not_nil!
update_attributes = defaults.nil? ? updates : defaults.not_nil!.merge(updates)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

Add an #update_or_create method to query sets

2 participants