Models and ember-data

Overview

The name of the FILE is the name of the model. For example, if the filename is app/models/pets.js, then the name of the model is "pets".

A model’s data is sent to a Controller or a Component, which will then usually get displayed in a template.

A model’s data comes from an Adapter that is hooked to a Fixture or an ember-data Store.

Fixture Data

Using the ember-data module, you can create a static data store that is helpful during experiments and prototyping. You’ll need to:

  1. Create a DS.FixtureAdapter for Ember to use.
  2. Create a Model.
  3. Tell your route where to find the data.

1. Create a DS. FixtureAdapter

Using Ember CLI, enter ember generate adapter application

It would have created the file app/adapters/application.js. Replace its content with:

import DS from 'ember-data';

export default DS.FixtureAdapter.extend({});

2. Create a Model

Using Ember CLI, enter ember generate model modelName

It would have created the file app/models/modelName.js

Now, you will need to first define the structure of the model (list of the fields and data type), and then reopen the class to enter the data. This can be done similar to this:

import DS from 'ember-data';

export default DS.Model.extend({
	title: DS.attr('string'),
	needs: DS.attr('string'),
	assests: DS.attr('string'),
	activities: DS.attr('string'),
	resources: DS.attr('string'),
}).reopenClass({
	FIXTURES: [
	{
		id:1, //Note: You MUST use a primary key called "id".
		title: 'Reduction in Space Travel Time to Saturn',
		needs: 'Reduce flight time',
		assests: 'Large budget',
		activities: 'Engineering',
		resources: 'Large research staff'
	},
	{
		id:2,
		title: 'Application Development Time',
		needs: 'Reduce time needed to learn a new language',
		assests: 'Lynda.com',
		activities: 'Experiment',
		resources: 'Some paid time'
	},
	{
		id:3,
		title: 'Yield of Hop Harvest',
		needs: 'Increase the number of hops produced per square yard of land.',
		assests: 'Fertilizer',
		activities: 'Pruning',
		resources: 'Only one farmer'
	}
	]
});

3. Associate the data to your route

In your route, app/routes/modelName.js, you’ll need to specify where to find the data using .find() or a similar method. For example:

import Ember from 'ember';
 	
export default Ember.Route.extend({
	model: function() {
		return this.store.find('logic');
	}
});