Skip to content

Use linkage: always: true on belongs_to relationships - #168

Merged
richmolj merged 3 commits into
graphiti-api:masterfrom
jkeen:relationship-linkage-for-belongs-to
Aug 19, 2019
Merged

richmolj merged 3 commits into
graphiti-api:masterfrom
jkeen:relationship-linkage-for-belongs-to

Conversation

@jkeen

@jkeen jkeen commented Aug 13, 2019

Copy link
Copy Markdown
Collaborator

This addresses issue #167

I'm unsure how to test this in the current suite. All the tests pass, but there's nothing explicitly testing this behavior. I tried modifying some tests in sideloading_spec.rb, but there's something with the way those PORO objects are working that don't trigger the related_resources like the tests in my rails app seem to do. Thought this would be a good starting point based off the discussion @wagenet and I had today, though.


# include relationship links for belongs_to relationships
# https://github.com/graphiti-api/graphiti/issues/167
linkage always: true if sideload_ref.type == :belongs_to

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This should do the trick for functionality. As far as code design goes, ideally the parent class wouldn't have to know about children. Maybe this could be an option that is overridden in the belongs_to subclass. We could also allow people to change the default value as well.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

yeah, could add an option. Based on what I described though, can you think of a reason someone wouldn't want this? It's still valid json-api, it's just more detailed json-api without a performance hit.

As for placement: I put it here to let jsonapi-serializable do the heavy lifting but I still have no idea why this doesn't seem to work in the tests, do you?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I agree might make sense to make this an option on Sideload generally, that is set for Sideload::BelongsTo:

# override
belongs_to :post do
  linkage_always(false)
end

# opt-in has many
has_many :comments do
  linkage_always(true)
end

You can see code for something like Sideload#assign_each as a reference. I'm not sure about the specs without seeing a failing example.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@jkeen, I can't see a good reason why someone might want to turn it off (though it's possible there is one), but I'm more interested in the case where you may want to turn it on for something else. This especially applies in the situation where your adapter isn't a relational database.

@jkeen

jkeen commented Aug 14, 2019

Copy link
Copy Markdown
Collaborator Author

Added an option to enable this, but it seemed to make more sense as an option on the relationship method instead of a method call inside the block like @richmolj illustrated above, as it didn't really need a block—just a boolean

So now:

belongs_to :position, linkage_always: false will override the default of true for belongs_to
has_many :position, linkage_always: true will override the default of false for has_many

This works great in my tests with Postman against my rails app, but the specs I added fail in a mysterious way, I believe due to related_resources being empty here: https://github.com/jsonapi-rb/jsonapi-serializable/blob/02e9e4df43a94528a56ffc4d71a630e81e9841f2/lib/jsonapi/serializable/relationship.rb#L47

Any insight into that?

@wagenet wagenet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks again for your work on this. Apologies for nitpicking!

Comment thread lib/graphiti/sideload.rb Outdated

@linkage_always = if opts[:linkage_always].nil?
# option not provided, use default
type == :belongs_to

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I still think I'd rather have this class not know about the actual types. (Though I guess there is some precedence with the apply_belongs_to_many_filter stuff...)

What if in Graphiti::Sideload::BelongsTo we do:

def initialize(name, opts)
  opts = { linkage_always: true }.merge(opts)
  super(name, opts)
end

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is what I was thinking 👍

Comment thread lib/graphiti/sideload.rb Outdated
@polymorphic_child = opts[:polymorphic_child]
@parent = opts[:parent]

@linkage_always = if opts[:linkage_always].nil?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I realize this is copied from jsonapi-rb, but the naming is a bit confusing to me. I feel like always_include_identifiers more accurately gets at what we want, though it does feel a touch long.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

yeah, I don't love the linkage_always name either. Agreed on better clarity with your suggestion, but having include in there might be confusing since this doesn't have anything to do with the included payload, but the rather the relationship.

what about resource_identifiers = :always vs resource_identifiers = :auto?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

I don't love the non-boolean, but it is descriptive. Maybe :when_included instead of :auto

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

nah, you're right. boolean and always_ is most descriptive. I went with always_include_resource_ids

@richmolj

richmolj commented Aug 14, 2019 •

Copy link
Copy Markdown
Contributor

On the tests:

The first two fail because PORO::Employee#positions will return an empty array by default (whereas ActiveRecord will fire a method to grab the positions).

sideloading_spec.rb:404 fails because there's no params[:include] = 'employee'

haven't checked the last one but that should be the brunt of it

@jkeen

jkeen commented Aug 14, 2019 •

Copy link
Copy Markdown
Collaborator Author

@richmolj sideloading_spec.rb:404 is testing the default behavior without the linkage, so I think it's just the other problem you said. How should I load up those positions manually then in the PORO without params[:include]?

@richmolj

Copy link
Copy Markdown
Contributor

Ah, my mistake. Just for this spec I would do something like allow_any_instance_of(PORO::Employee).to receive(:positions) { [position1, position2] }

@jkeen
jkeen force-pushed the relationship-linkage-for-belongs-to branch from 113ffc2 to d953749 Compare August 15, 2019 18:14
@jkeen

jkeen commented Aug 15, 2019

Copy link
Copy Markdown
Collaborator Author

Cleaned up some things and split out tests into a separate file

…n sideload to override default, split out tests into own file
@jkeen
jkeen force-pushed the relationship-linkage-for-belongs-to branch from d953749 to 30b6e9b Compare August 15, 2019 20:38
@jkeen

jkeen commented Aug 15, 2019

Copy link
Copy Markdown
Collaborator Author

@richmolj @wagenet I think this is all set if you're alright with that name. Naming is the hardest part.

@wagenet wagenet left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Looks good to me, though a sanity check from @richmolj wouldn't hurt.

@richmolj richmolj left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM!

@richmolj
richmolj merged commit c3aa6fe into graphiti-api:master Aug 19, 2019
richmolj pushed a commit to richmolj/graphiti that referenced this pull request Oct 21, 2019
PR graphiti-api#168 introduced N+1 by
default. This removes that as the default option, and we'll look into it
more in a future PR.
@richmolj richmolj mentioned this pull request Oct 21, 2019
LeipeLeon added a commit to Memoriam-tv/graphiti-api.github.io that referenced this pull request Aug 10, 2021
richmolj pushed a commit to graphiti-api/graphiti-api.github.io that referenced this pull request Aug 10, 2021
jkeen added a commit that referenced this pull request Aug 7, 2026
A belongs_to sent only a link in 1.x, and to learn the id took a second request. That id is the foreign key already on the parent, so rendering it loads nothing extra (which was not the case with #168 which caused #185 to revert it)

A belongs_to that cannot use its foreign key still loads the association, so it stays opt-in behind always_include_resource_ids, as does has_many. That covers a scope or params block, a base_scope, a polymorphic or remote target, and a custom primary_key.

always_include_resource_ids_by_default now sets this per resource, replacing the monkey patch #167 has been recommending since 2020.

Closes #167
github-actions Bot pushed a commit that referenced this pull request Aug 7, 2026
# [2.0.0-beta.4](v2.0.0-beta.3...v2.0.0-beta.4) (2026-08-07)

### Bug Fixes

* a subclass redeclaring a relationship reaches its serializer ([976dbc4](976dbc4))
* make each appraisal test the Rails version it is named for ([9e00652](9e00652))
* require active_support so graphiti boots without Rails ([d431a03](d431a03))

### Code Refactoring

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

### Features

* belongs_to renders resource linkage by default ([024824d](024824d)), closes [#168](#168) [#185](#185) [#167](#167) [#167](#167)
* 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)
* handle exceptions with rescue_registry, fold in graphiti_errors ([e48171c](e48171c))
* require Ruby 3.2 and Rails 7.1 ([635b249](635b249))

### 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.
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants