brownie3003
brownie3003

Reputation: 538

HasMany - BelongsTo with RESTAdapter Ember.js

Trying to create a has many belongs to with RESTAdapter. In essence I have a card (twitter user) that has many hashtags. I'm using ember-cli.

My models:

//models/card.js
import DS from 'ember-data';

export default DS.Model.extend({
    handle: DS.attr('string'),
    bio: DS.attr('string'),
    avatar: DS.attr('string'),
    hashtags: DS.hasMany('hashtag')
});


//models/hashtag.js
import DS from 'ember-data';

export default DS.Model.extend({
    title: DS.attr('string'),
    print: DS.attr('boolean'),
    card: DS.belongsTo('card')
});

My Card Route

import Ember from 'ember';

export default Ember.Route.extend({
    model: function(){
        return this.store.createRecord('card');
    },

    actions: {
        submitHandle: function () {
            var card = (this.currentModel);
            var store = this.store;
            var hashtag = store.createRecord('hashtag');

            card.set("bio", "testbio");
            card.set("avatar", "twitter.com/129012931/img_original.jpg");

            hashtag.set("title", "EmberJS");
            hashtag.set("print", false);
            hashtag.set("card", card);

            card.get('hashtags').addObject(hashtag);

            card.save();
        }
    }
});

In my route when the user puts in a twitter name I am making up a dummy card and hashtag. I add the hashtag to the cards hashtags. It all works great up to this point on the ember side. If I don't call card.save(), the card and hashtag are associated as expected. When I call .save() the request posted is:

card: {handle: "@testing123", bio: "testbio", avatar: "twitter.com/129012931/img_original.jpg"}

No mention of the hashtag.

I'm using sails for the back end which seems to save whatever is provided in the request.

If I try something like: hashtag.save().then(function () { card.save() });

Which I tried because I thought I might need an ID from the server for the hashtag before Ember could associate it with the card. The hashtag request is as follows:

{"hashtag":{"title":"EmberJS","print":false,"card":null}}

And the card request:

{"card":{"handle":"@wiolsid","bio":"testbio","avatar":"twitter.com/129012931/img_original.jpg"}}

Upvotes: 2

Views: 367

Answers (1)

A couple of newbie considerations.

  1. Try creating a hashtag like this:

    var hashtag = store.createRecord('hashtag', {card: card});
    

    Then you don't need card.get('hashtags').addObject(hashtag);.

  2. Save the child model before saving the parent model.

Here's a fiddle i had created to try out a similar task:

Upvotes: 1

Related Questions