Nirmalya Ghosh
Nirmalya Ghosh

Reputation: 2510

hasMany association in Ember js

app/models/card.js

export default Model.extend({
  title: attr('string'),
  description: attr('string'),
  users: hasMany('user')
});

app/models/user.js

export default Model.extend({
  email: attr('string'),
  name: attr('string')
});

app/routes/card/new.js

actions: {
  save(title, description) {
    const newCard = this.get('store').createRecord('card', {
      title,
      description
    });

    this.get('store').findRecord('user', 1).then(function(user) {
      newCard.set('users', user);
      console.log(newCard);
    });

    newCard.save().then((card) => {
      // go to the new item's route after creating it.
      this.transitionTo('card.card', card);
    });
  }
}

So, when I'm saving a card, it is throwing me this error:

Assertion Failed: You must pass an array of records to set a hasMany relationship.

I want to create an association between the newly created card and the user.

Other info:

Repo link: https://github.com/ghoshnirmalya/hub-client

Ember : 2.6.1

Ember Data : 2.6.1

Upvotes: 2

Views: 331

Answers (1)

Lux
Lux

Reputation: 18240

You defined that a card has many users:

users: hasMany('user')

So you can's set 'users' to a single user:

newCard.set('users', user);

So you could either change the hasMany to a belongsTo, or set the 'users' instead to just one user to an array of users: [user]

Upvotes: 1

Related Questions