Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember-data createRecord with hasMany relationship without saving

I want to create a new site record. The model looks like:

var SiteModel = DS.Model.extend({
    name: attr(),
    ...

    languages: DS.hasMany('language'),
});

The language property describes in which languages the content of a site can be written. To create the form, I need to create a model in my route. So I want to create a new record, without saving this one to the db:

 var WebsitesNewRoute = Ember.Route.extend({
     model: function() {
         return this.store.createRecord('site', {
              languages: Ember.A()
         });
     }
 }

That does not work as intended, as I got the following error: cannot set read-only property "languages" on object: <app@model:site::ember1012:null>>. Why is the languages property readOnly? As far as I know I did not configure that in my model...


I know the question Ember Data- createRecord in a hasMany relationship, but in my case I don't want to save anything yet (I only want to create the model, so I could use it in my template).

like image 291
Jacob van Lingen Avatar asked Jun 12 '14 12:06

Jacob van Lingen


People also ask

Which of the following Cannot be a reflexive relationship in Ember?

<br> `therefore` 512 cannot be the number of reflexive relations defined on a set A.

What are polymorphic models in Ember?

Polymorphism. Polymorphism is a powerful concept which allows a developer to abstract common functionality into a base class. Consider the following example: a user with multiple payment methods. They could have a linked PayPal account, and a couple credit cards on file.

What is store in Ember?

One way to think about the store is as a cache of all of the records that have been loaded by your application. If a route or a controller in your app asks for a record, the store can return it immediately if it is in the cache.


1 Answers

Ember-Data defines languages as a read-only property because it doesn't want you to replace the array. No matter if you're saving or not, Ember-Data wants you to add relationships with addObject and remove relationships with removeObject.

So if you wanted to add a language, you would do this:

model: function() {
    var model = this.store.createRecord('site');
    var language = getLanguage();
    model.get('languages').addObject(language);
    return model;
}

What you're doing by giving languages to createRecord, is essentially calling model.set('languages', Ember.A()), and Ember-Data doesn't like that.

It's dumb, I know, but that's just how Ember-Data works.

like image 50
GJK Avatar answered Oct 02 '22 16:10

GJK