graphiti-api/spraypaint.js

Constructor vs. direct persisted relationship assignment differences

Closed this issue · 1 comments

elDub commented

Using a simple relationship between a Company and Country, and when the Country is already persisted:

@Model()
export class Country extends ApplicationRecord {
  static jsonapiType = "countries"

  @Attr() name: string
}

@Model()
export class Company extends ApplicationRecord {
  static jsonapiType = "companies"

  @Attr() name: string
  @BelongsTo() country: Country
}
var country = new Country({ id: '123', name: 'USA' });
country.isPersisted = true;

Creation via direct assignment appears to work normally (it establishes a relationship):

var company = new Company({ name: 'ACME' });
company.country = country;
company.save({ with: 'country' });
{"data":{"type":"companies","attributes":{"name":"ACME"},"relationships":{"country":{"data":{"type":"countries","id":"123","method":"update"}}}},"included":[{"type":"countries","id":"123"}]}

While creation via the constructor does not (it does not establish the relationship):

var company = new Company({ name: 'ACME', country: country });
company.save({ with: 'country' });
{"data":{"type":"companies","attributes":{"name":"ACME"}}}

An identifiable difference between the two approaches (just before the save is performed) is that via the constructor company._originalRelationships is populated with information related to the country, while during direct assignment it is empty.

Now fixed in 0.10.8 due to the amazing @nobitagit !