Skip to content

Commit

Permalink
fix(ErrorMessages): Improve error message when attempting to set rela…
Browse files Browse the repository at this point in the history
…tionships on unloaded entities
  • Loading branch information
elpete committed Jul 24, 2020
1 parent ab8e121 commit fe4ad26
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 3 deletions.
10 changes: 10 additions & 0 deletions models/BaseEntity.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -2680,6 +2680,16 @@ component accessors="true" {
return invoke( this, relationshipName );
} );

if (
relationship.relationshipClass != "BelongsTo" &&
relationship.relationshipClass != "PolymorphicBelongsTo"
) {
guardAgainstNotLoaded(
"This instance is not loaded so it cannot set the [#relationshipName#] relationship. " &
"Save the new entity first before trying to save related entities."
);
}

return relationship.applySetter( argumentCollection = arguments.missingMethodArguments );
}

Expand Down
4 changes: 1 addition & 3 deletions tests/specs/integration/BaseEntity/SubqueriesSpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -100,9 +100,7 @@ component extends="tests.resources.ModuleIntegrationSpec" appMapping="/app" {
} );

it( "can add a subselect using a belongsTo relationship with multiple foreign keys", function() {
var game = getInstance( "Game" )
.addSubselect( "fieldName", "field.fieldName" )
.findOrFail( 1 );
var game = getInstance( "Game" ).addSubselect( "fieldName", "field.fieldName" ).findOrFail( 1 );
expect( game.getFieldName() ).notToBeNull();
expect( game.getFieldName() ).toBe( "Second Field" );
expect( variables.queries ).toHaveLength(
Expand Down
14 changes: 14 additions & 0 deletions tests/specs/integration/GoodErrorMessagesSpec.cfc
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,20 @@ component extends="tests.resources.ModuleIntegrationSpec" appMapping="/app" {
regex = 'This instance is missing \`accessors\=\"true\"\` in the component metadata\. This is required for Quick to work properly\. Please add it to your component metadata and reinit your application\.'
);
} );

it( "throws a helpful error message when trying to set a belongsToMany relationship when the relationship is not loaded", function() {
expect( function() {
getInstance( "Post" ).create( {
"user_id" : 1,
"body" : "A new post body",
"publishedDate" : now(),
"tags" : [ 1, 2 ]
} );
} ).toThrow(
type = "QuickEntityNotLoaded",
regex = "This instance is not loaded so it cannot set the \[tags\] relationship\. Save the new entity first before trying to save related entities\."
);
} );
} );
}

Expand Down

0 comments on commit fe4ad26

Please sign in to comment.