Sang Park
Sang Park

Reputation: 402

Ember Data: create Model without store

Is there a way to create a DS.Model object without using store.createRecord ?

EDIT

maybe I need to give some context.

I am writing an Ember Addon that has a few model that are not bridged through the app/ directory and I want to write unit tests for those model. The auto generated unit tests uses moduleForModel helper which works fine if the model is bridged. But since my models are not bridged, they don't get merged to the dummy application's namespace and moduleForModel helper couldn't find the model.

This is why I wanted to be able to create model without using store object since I couldn't figure out a way to have access to store without using moduleForModel helper.

Upvotes: 8

Views: 2544

Answers (2)

oleksandr.kazimirchuk
oleksandr.kazimirchuk

Reputation: 839

Yes, there is. You can push your plain javascript object (that must have appropriate keys as defined in your model definition) into the store. In terms of Ember, such object is called hash. Here's the guide for you. Be careful, after pushing your hash into the store, the created model will not be new and dirty. It will have state root.loaded.saved. More about states here

Hope I helped you.

Upvotes: 0

Max Wallace
Max Wallace

Reputation: 3758

No. DS.Model is an Ember.Object, so if it were possible, we would use create:

const User = DS.Model.extend({
  firstName:   DS.attr('string'),
  lastName:    DS.attr('string'),
});

const foo = User.create({ firstName: 'Foo', lastName: 'Bar' });

> Uncaught EmberError { message: "You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.", ... ]

DS.Model instances are linked back to the store by design (that's how they receive updates when new data is pushed in) so it doesn't make sense to create a DS.Model instance without that connection. Ember Data makes this explicit by requiring you to call createRecord on your store instance.

Upvotes: 2

Related Questions