Ember-data createRecord with hasMany relationship without saving

I want to create a new site record. The model is as follows:

var SiteModel = DS.Model.extend({ name: attr(), ... languages: DS.hasMany('language'), }); 

The language property describes in which languages ​​the contents of the site can be written. To create a form, I need to create a model on my route. Therefore, I want to create a new record without saving it in db:

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

This does not work as I received 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 this in my model ...


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

+6
source share
1 answer

Ember-Data defines languages as a read-only property because it does not want you to replace the array. Regardless of whether you save or not, Ember-Data wants you to add relationships with addObject and delete relationships with removeObject .

So, if you want to add a language, you would do the following:

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

What you do by supplying languages before createRecord essentially calls model.set('languages', Ember.A()) , and Ember-Data doesn't like that.

This is stupid, I know, but this is how Ember-Data works.

+6
source

Source: https://habr.com/ru/post/970744/


All Articles