1

I don't understand which one of the following ways make more sense in the Ember workflow. What is cleaner?

It is better to have one model like in this code?

app/routes/index.js

import Ember from 'ember';

export default Ember.Route.extend({
  model: function() {
    return {
      categories: this.store.find('category'),
      products: this.store.find('product')
    };
  }
});

Or is it better to not use model at all like in this code?

app/routes/index.js

import Ember from 'ember';

export default Ember.Route.extend({
  categories: function() {
    return categories: this.store.find('category')
  },
  products: function() {
    return products: this.store.find('product')
  }
});

Or are both ways fine and I shouldn't worry about this?

wintermeyer
  • 8,178
  • 8
  • 39
  • 85

2 Answers2

2

The first code is definitely the correct "Ember way". categories and products will appear as properties on your controller's model, so from your template you can do stuff like this:

{{#each category in model.categories}}<!-- use category -->{{/each}}

I'm not even sure how you would use your second code. Controller won't be able to reach them at all.

panta82
  • 2,763
  • 3
  • 20
  • 38
1

Both ways do not have any significant differences other than syntax. One thing to note in the second part is that you have a syntax error. There is no need for the categories : portion, you can just directly return the promise from store.find. Furthermore, you should make the two functions into computed properties using .property() so they can be treated the way a model is treated. Right now they are just functions so they cannot be observed which is what you want in most cases. Here is how your second option should look like:

categories: function() {
    return this.store.find('category');
}.property(),

products: function() {
    return this.store.find('product');
}.property()

I do agree with @panta that the first way is the "Ember" way though. I can see the second way being useful when you only want to obtain a relevant portion of the model, not the whole thing.

Let's say your model is a warehouse that has products and product categories but also things like name, address and such.

{
    name: "My Warehouse",
    size: 10,
    address: "123 St"
    // ... other properties
    products: // ...
    categories: // ...
} 

Then you can conveniently obtain from the store only the data you actually need in a particular controller (while you load the actual warehouse model somewhere else):

categories: function() {
    return this.store.all('category'); // use .all to get all records currently in the store
}.property(),

products: function() {
    return this.store.all('product'); // use .all to get all records currently in the store
}.property()
nem035
  • 34,790
  • 6
  • 87
  • 99