Skip to content

08.0.0 hasMany Associations

Patrick Baselier edited this page Oct 22, 2015 · 2 revisions

What you will learn

  • Define and render a hasMany association
  • Change a timestamp into human readable format

Before you start

See the installation instructions. Use tag 8.0.0.

Render Reviews

  • Open frontend/app/templates/products/show.hbs.
  • Remove all but one <div class='row'> elements and the subsequent <hr/> tag from their <div class='reviews'> container.
  • Wrap the remaining <div> in the Handlebars {{each}} helper:
  {{#each model.reviews as |review|}}
    <div class='row'>
    ...
    </div>
    <hr/>
  {{/each}}
  • Open frontend/app/models/product.js and add a reviews association:
export default DS.Model.extend({
  ...
  image: DS.attr(),
  reviews: DS.hasMany('review')
});
  • Inspect the error shown in the Console tab in the browser. Ember doesn't know the review model yet. Let's define it.
  • In the frontend folder, enter the command ember g model review.
  • Open frontend/app/models/review.js and add the following attributes:
export default DS.Model.extend({
  description: DS.attr(),
  rating: DS.attr(),
  user: DS.attr(),
  createdAt: DS.attr()
})
  • Open frontend/app/templates/products/show.hbs and replace:
    • Anonymous with {{review.user}}
    • 10 days ago with {{review.createdAt}}
    • See more snippets like this... with {{review.description}}

Format time

Here you will install and use Ember-moment to use moment.js for formatting the creation date of the review, so it can display 4 days ago instead of something like 2015-10-26T14:07:33.926Z.

  • In the frontend folder, enter the command ember install ember-moment@4.1.0.
  • Open frontend/app/templates/products/show.hbs and replace {{createdAt}} with {{moment-from-now createdAt}}.