TLT: Loading An Initial Record At The Index Using the Ember-CLI

I'm developing a site that requires I display the data in a particular database entry upon visiting the site's index. I'm using EmberJS and the Ember-CLI to build the front-end and on the back is a Django REST API. During development, I'm using Ember fixture data.

Reminder "TLT" stands for "The Little Things." 'TLT' is the tag I use to represent posts that cover really, really small technical details. They're usually very short posts.

Problem

I have a number of records (database objects). I want to display one of those records when a user initially enters my site. So, when a user hits mysite.com/, what's displayed should be one of those records.

Solution

Start by constructing a model with fixtures. If you're not working with fixtures, this doesn't pertain to you:

$> ember generate model blogpost

Now, in app/models/blogpost.js:

import DS from 'ember-data';

export default DS.Model.extend({  
    title: DS.attr('string'),
    body: DS.attr('string')
}).reopenClass({
    FIXTURES: [
        {
            id: 1,
            title: "My Blog Post",
            body: "This is a verse body..."
        }
});

Construct a route:
$> ember generate route blogposts

In routes/blogposts.js:

import Ember from 'ember';

export default Ember.Route.extend({  
    model: function() {
        // all we want is the first record
        return this.store.find('blogpost', 1);
    },
});

Configure your main Router.

In app/router.js:

import Ember from 'ember';  
import config from './config/environment';

var Router = Ember.Router.extend({  
  location: config.locationType
});

Router.map(function() {  
    this.route('blogposts', { path: '/' });
});

export default Router;  

Finally, construct a template:
$> ember generate template blogposts

In templates/blogposts.hbs:

<div id="panel">  
  <h3>{{model.title}}</h3>
 </div>
{{outlet}}

That's it!

Greg

Software Engineer

Subscribe to GregBlogs