Saving an entity with new hasMany assocation objects in a single request

When submitting a model with a hasMany relationship is there a way, using the default JSON::API adapters, to submit new objects from that relationship in a single request? For example, if I have a model:

export default class TicketModel extends Model {
  @attr('string') name;
  . . .

  @belongsTo('org', { async: true }) org;
  @hasMany('component', { async: true }) components;
  @hasMany('account-ticket') accountTickets;

I have no problem submitting a save and having the component association persisted since the components already exist and have an existing id.

  Parameters: {"data"=>{"id"=>"4", 
"attributes"=>{"name"=>"Test with reviewer", ...}, 
  "org"=>{"data"=>{"type"=>"orgs", "id"=>"1"}}, ..., 
  "components"=>{"data"=>[{"type"=>"components", "id"=>"1"}, {"type"=>"components", "id"=>"124"}, {"type"=>"components", "id"=>"123"}]}}, 
"id"=>"4", "ticket"=>{}}

But, I create the account ticket models in the form so they don’t have an id. What I was hoping I’d see in the submission is something like:

"relationships" => {
  "account-tickets" => { "data" => [
    {"type"=> "account_tickets", "role" => "manager", "account_id"=> 1}
. . .

So that I could create those relationships on the fly on the server side. Is this outside of the “default” ember-data json::api behavior?

It is outside the default behavior for that adapter and serializer, though I always recommend writing your own.

The feature you’ll want to make use of is identifiers. Every record is assigned a unique identifier and so long as data returned from the api is also assigned that identifier (either manually in your adapter or reflected by your api) then your save will work correctly.

1 Like

Thank you . I’ve going to give this a shot. I’ve been in an an ember-simple-auth spiral for a few days so I havn’t had a chance to get back to this.