Skip to content

feat!: the model you inspect is the model that saves - #465

Merged
jkeen merged 4 commits into
graphiti-api:betafrom
jkeen:feature/data-access
Jul 30, 2026
Merged

jkeen merged 4 commits into
graphiti-api:betafrom
jkeen:feature/data-access

Conversation

@jkeen

@jkeen jkeen commented Feb 27, 2024 •

Copy link
Copy Markdown
Collaborator

Description

Today a resource goes straight from request payload to saved record — there is no point at which you can hold the model with attributes applied but nothing written. That makes ordinary Rails patterns awkward: inspecting what a request would change, running authorization against the resulting object, or adjusting an attribute before save.

This makes proxies assign lazily and exposes the unsaved model. The instance you inspect is the instance that saves — unconditionally.

Creates

resource = MyResource.build(params)
resource.data          # => unsaved model, attributes applied
resource.data.valid?   # inspect before committing to anything
resource.save

Updates

resource = MyResource.find(params)
resource.assign_attributes(params)  # Rails-style, takes request params
resource.data.changed               # dirty tracking works
resource.update

# or assign and save in one call, Rails-style
resource = MyResource.find(params)
resource.update(params)

What changed

  • Resource.build(params) returns a proxy whose #data is the built, attribute-applied model rather than resolving a scope (also fixes my_resource.data raises Graphiti::Errors::RecordNotFound in #create action after Graphiti::Resource#build(params) when the table is empty #458).
  • ResourceProxy#assign_attributes(params) applies the payload to the model without saving. Idempotent per payload — repeated calls don't re-fire the attributes callbacks.
  • Attributes are assigned once, before the persistence hooks fire. save persists the assigned instance; only process_belongs_to-derived foreign keys are applied at save time.
  • Validation runs before assignment, and doesn't re-run at save when the payload was already validated — writable guards evaluate the same number of times whether or not you inspect the model.
  • Ships UPGRADING.md in the gem.

BREAKING CHANGES (hence the beta / 2.0 target)

around_persistence receives the assigned model, not the attributes hash. Its pre-yield position is now the last chance to touch the model before save, inside the transaction. Hooks that mutate the attributes hash before yield must move that change to before_attributes (same mutable-hash idiom, runs before assignment) or set it on the model. Hooks that only wrap their yield are unaffected. Graphiti 1.x warns at runtime for affected hooks (#514).

Custom create/update overrides + inspected models. If callers inspect the model before saving, the override must accept it: def create(attributes, meta = nil, assigned_model: nil). Without the keyword, saving an inspected proxy raises Graphiti::Errors::AssignedModelNotSupported instead of silently discarding changes. Save-only usage is unaffected.

Notes

  • If you inspect the model before saving, the attributes callbacks run at inspection time, outside the save transaction. On the plain save path they run inside the transaction, at the same point as 1.x — save-only code sees no behavior change.
  • Writable guards judge persisted state; they never see the current request's unsaved changes.
  • #data exposes the pre-assigned root model; sideposted children are still built and assigned during save.

@jkeen
jkeen force-pushed the feature/data-access branch from fec4590 to 2882008 Compare February 28, 2024 15:34
@jkeen
jkeen force-pushed the feature/data-access branch 3 times, most recently from 5d66f76 to bbacf6f Compare March 28, 2024 02:09
@jkeen
jkeen force-pushed the feature/data-access branch 2 times, most recently from 26a3820 to 8997e49 Compare September 22, 2024 19:35
@jkeen
jkeen marked this pull request as ready for review July 28, 2026 13:22
@jkeen
jkeen force-pushed the feature/data-access branch from 88a8209 to 5a5c6e0 Compare July 28, 2026 16:20
@jkeen jkeen changed the title Provide access to underlying model during build/update/save process closer mirroring rails patterns feat: expose the unsaved model before saving Jul 28, 2026
@jkeen
jkeen force-pushed the feature/data-access branch 2 times, most recently from 5a5c6e0 to 1062fbd Compare July 30, 2026 18:11
@jkeen jkeen changed the title feat: expose the unsaved model before saving feat!: the model you inspect is the model that saves Jul 30, 2026
@jkeen
jkeen changed the base branch from main to beta July 30, 2026 19:45
jkeen added 3 commits July 30, 2026 14:47
…closer mirroring rails controller patterns.

Changes:
 - (for creates):
	@resource = MyResource.build(params);
	@resource.data #=> unsaved model with attributes applied
 - (for updates):
	@resource = MyResource.find(params);
	@resource.assign_attributes
	@resource.data #=> unsaved model with attributes applied
Attributes are assigned once, before the persistence hooks fire, and the assigned model is the instance that saves. Replaces the freeze guard and arity sniffing from earlier revisions. Ships UPGRADING.md.

BREAKING CHANGE: around_persistence hooks receive the assigned model instead of the attributes hash. Move attribute-hash modifications to before_attributes, or set values on the model. Custom create/update overrides that should receive a pre-assigned model must accept an assigned_model: keyword.
@jkeen
jkeen force-pushed the feature/data-access branch from 0248d11 to e99fb59 Compare July 30, 2026 20:32
@jkeen
jkeen merged commit a905fff into graphiti-api:beta Jul 30, 2026
44 checks passed
github-actions Bot pushed a commit that referenced this pull request Jul 30, 2026
# [2.0.0-beta.1](v1.12.2...v2.0.0-beta.1) (2026-07-30)

### Features

* drop Ruby 2.7 and Rails 5.2 support ([e905ddb](e905ddb))
* the model you inspect is the model that saves ([#465](#465)) ([a905fff](a905fff))

### BREAKING CHANGES

* around_persistence hooks receive the assigned model instead of the attributes hash. Move attribute-hash modifications to before_attributes, or set values on the model. Custom create/update overrides that should receive a pre-assigned model must accept an assigned_model: keyword. See UPGRADING.md
* Ruby >= 3.0 / Rails >= 6 are now required.
@github-actions

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 2.0.0-beta.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

@jkeen jkeen mentioned this pull request Aug 9, 2026
github-actions Bot pushed a commit that referenced this pull request Sep 1, 2026
# [2.0.0](v1.13.3...v2.0.0) (2026-09-01)

### Bug Fixes

* a subclass redeclaring a relationship reaches its serializer ([976dbc4](976dbc4))
* accept a single value for array filters ([#517](#517)) ([ee685b6](ee685b6))
* always render included when the client asked to include ([8691b3f](8691b3f))
* apply sideloads at definition once setup! has run ([39ef393](39ef393)), closes [#524](#524)
* autolink = true no longer clobbers an inherited :on_demand ([2d26f8c](2d26f8c))
* bridge the last 1.x names that died with a bare NameError ([34e1dbd](34e1dbd))
* build the entity map when the root query is, not on first use ([134d18b](134d18b))
* coerce debug flags from env strings ([46be6aa](46be6aa))
* compare each concurrency path against itself in the table to better illustrate the performance wins ([d0f0e92](d0f0e92))
* compare the endpoint id to the payload id as strings ([62051d7](62051d7))
* drop the relationship guard install notice ([c204312](c204312))
* evaluate writable guards under the action being performed ([d56b86a](d56b86a))
* **generators:** stop injecting a routes host into config/application.rb ([db92d06](db92d06))
* give client-caused errors real detail and stop 500ing on bad query params ([35acc3e](35acc3e)), closes [#531](#531)
* keep a belongs_to linkage when another include shares its name ([2c9c7c7](2c9c7c7))
* keep a customized sideload's instances out of entity dedup ([b1beee3](b1beee3))
* keep deep filters narrow when an include path repeats ([833a10b](833a10b))
* keep rake task helpers out of the global namespace ([0a41a60](0a41a60)), closes [graphiti-api/graphiti-rails#91](graphiti-api/graphiti-rails#91)
* keep request state in fiber storage so it survives into child fibers ([6569935](6569935))
* let an abstract resource declare relationships ([6036392](6036392)), closes [#453](#453)
* make each appraisal test the Rails version it is named for ([9e00652](9e00652))
* only register the jsonapi mime type when it is missing ([88401ab](88401ab))
* raise a more helpful named error when belongs_to linkage reads an unselected foreign key ([f59ea0b](f59ea0b))
* read the links param from the query, not the context object ([3b934cb](3b934cb))
* reject a non-object data payload instead of raising TypeError ([51603b8](51603b8))
* reject invalid page parameters ([#537](#537)) ([bb3698b](bb3698b)), closes [#347](#347)
* remove the unused ActiveRecord adapter create and update ([b66fb8e](b66fb8e))
* require active_support so graphiti boots without Rails ([d431a03](d431a03))
* require rescue_registry 1.1 for the fiber storage fix ([ac63996](ac63996))
* resolve inline when already on a sideload pool thread ([11c9de7](11c9de7))
* scope debugger chunks to the request rather than the class ([9a77896](9a77896))
* stop assigning the same child twice when a resource repeats in the include path ([588503b](588503b))
* surface the first child error from concurrent polymorphic sideloads ([5a08c0e](5a08c0e))
* treat empty polymorphic configuration as unset ([#538](#538)) ([5c17899](5c17899)), closes [#199](#199)
* typecast null values in filter lists ([#515](#515)) ([3756fd1](3756fd1))
* Update some missing sections and terms after renames, register unsupported pagination error ([39cff19](39cff19))
* with_options accepts the predicate backed relationship options ([71ab441](71ab441))

### Code Refactoring

* bridge the remaining 1.x names ([3d80ef9](3d80ef9))

### Features

* add full set of commented-out Resource defaults in ApplicationResource when using the generator ([367678e](367678e))
* Add graphiti:audit task to audit resources for issues ([84436ea](84436ea))
* add rspec matchers for resource relationships and attributes ([70525f7](70525f7)), closes [graphiti-api/graphiti_spec_helpers#14](graphiti-api/graphiti_spec_helpers#14)
* add schema rake tasks, so checking a schema no longer means running the suite ([6f4783d](6f4783d))
* belongs_to renders resource linkage by default ([024824d](024824d)), closes [#168](#168) [#185](#185) [#167](#167) [#167](#167)
* carry CurrentAttributes into concurrent sideloads ([7092096](7092096))
* carry the assigned model on the resource, not through override signatures ([8ad848d](8ad848d))
* declare Graphiti's client errors in rescue_responses ([e369824](e369824))
* dedupe under concurrency and across distinct resources ([800b1a2](800b1a2))
* deduplicate sideloaded entities across include paths ([0c2829a](0c2829a))
* deprecate SpecHelpers::Sugar in favor of the full helper names ([b155849](b155849))
* drop Ruby 2.7 and Rails 5.2 support ([e905ddb](e905ddb))
* fold allow_nil and deny_empty into one blanks: filter option ([a108403](a108403))
* fold graphiti_spec_helpers into graphiti ([da955a1](da955a1))
* fold graphiti-rails into graphiti ([7740f8a](7740f8a)), closes [graphiti-rails#52](https://github.com/graphiti-rails/issues/52)
* **generators:** explicit rendering by default, respond_with only when Responders is included ([70741fe](70741fe))
* handle exceptions with rescue_registry, fold in graphiti_errors ([e48171c](e48171c))
* in-tree plain ruby and sinatra examples ([b92c6d9](b92c6d9))
* let the resource generator name the controller ([6ea7141](6ea7141)), closes [graphiti-api/graphiti-rails#53](graphiti-api/graphiti-rails#53)
* mark deprecated settings in the generated ApplicationResource ([52b0642](52b0642))
* move link rendering onto the resource as page_links and relationship_links ([57878d1](57878d1))
* move typecast_reads onto the resource and let the railtie own Rails config ([236e970](236e970))
* omit relationships that render no ids and no link ([916aa8c](916aa8c))
* one link mode per relationship, cascading from relationship_links ([f0e1da1](f0e1da1))
* point connection pool timeouts at the sizing formula and add an audit task to check ([6e017c6](6e017c6))
* raise MissingRelationshipMethod when rendering reads an association the model does not define ([1c41cee](1c41cee))
* rename always_include_resource_ids to resource_ids, with a belongs_to_resource_ids_by_default setting ([8b11151](8b11151))
* require Ruby 3.2 and Rails 7.1 ([635b249](635b249))
* ship the Rails application template in this repo ([76d5329](76d5329))
* split validate_endpoints into validate_requests and validate_links ([100a370](100a370))
* take error text from locale keys ([d01fd06](d01fd06)), closes [#216](#216)
* the model you inspect is the model that saves ([#465](#465)) ([a905fff](a905fff))
* write every error code Graphiti renders into the generated locale file ([15f19c1](15f19c1))

### Performance Improvements

* fingerprint the checkout being measured, not the working tree ([99656e1](99656e1))
* memoize whether a belongs_to renders ids from its foreign key ([dcb60b2](dcb60b2))
* nest the entity map instead of keying it by an array ([20bf625](20bf625))
* only deduplicate resources that two include paths can both reach ([744f014](744f014))
* record latest performance stats ([7380ef9](7380ef9))
* resolve a lone sideload inline rather than through the pool ([3415592](3415592))
* reuse the resolved data and proxies when building cache keys ([8a17350](8a17350))
* skip the on-demand link strip when no relationship renders links on demand ([cf86a8c](cf86a8c))
* skip the promise machinery when nothing is sideloaded ([d879923](d879923))
* skip zipping a lone sideload promise ([7ef2cea](7ef2cea))
* stop building a key for every record an association is checked against ([ccb5f71](ccb5f71))

### BREAKING CHANGES

* nothing removed, everything warns and goes away in 3.0. Except `include GraphitiErrors`, which now raises, as rescue_registry replaced it, so there's nothing to point it at.
* graphiti_errors is no longer a dependency and must be removed from the Gemfile, along with any `include GraphitiErrors`.

GraphitiErrors::Validation::Serializer is now Graphiti::ErrorSerializers::Validation, and GraphitiErrors.enable!/disable! becomes handle_request_exceptions. 409 responses now report code "conflict" and title "Conflict Error".
* Ruby >= 3.2 and Rails >= 7.1 are now required.
* remove graphiti-rails from your Gemfile. Controllers serving Graphiti resources must `include Graphiti::Rails::Controller` — previously every controller received it whether it wanted it or not. Graphiti::Responders is now Graphiti::Rails::Responders.
* remove graphiti_spec_helpers from your Gemfile. Prefer Graphiti::SpecHelpers and "graphiti/spec_helpers/rspec"; the old namespace and require paths still resolve, warn, and are removed in 3.0.
* around_persistence hooks receive the assigned model instead of the attributes hash. Move attribute-hash modifications to before_attributes, or set values on the model. Custom create/update overrides that should receive a pre-assigned model must accept an assigned_model: keyword. See UPGRADING.md
* Ruby >= 3.0 / Rails >= 6 are now required.
@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

🎉 This PR is included in version 2.0.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant