Nacho B
Nacho B

Reputation: 1619

Use a model to create an object in a component

I'm in Ember 3.4

I can create an EmberObject with

let course = EmberObject.extend({
  duration: null,
  level: null
});

course.create({ duration: '7', level: 'medium' });

But I already have a model for courses, defined in 'app/models/course.js'.

I wonder if I can "import" the model in the component and use it to create the object.

Upvotes: 0

Views: 44

Answers (1)

NullVoxPopuli
NullVoxPopuli

Reputation: 65093

yeah, you can call extend / create on any ember object.

Though, if you're wanting ember-data to be aware of the model, you may want to inject the store via a service.

like this:

import Component from '@ember/component';
import { service } from '@ember-decorators/service';

export default class extends Component {
  @service store;

  async someFunction() {
    const course = this.store.createRecord('course', {
      duration: '7', 
      level: 'medium'
    });

    // maybe other logic

    await course.save();

  }
}

To import anything from models'

import ModelName from 'appname/app/models/model-file';

Upvotes: 2

Related Questions