Route and resource

Now that you can nest routes, which is the main difference between routes and resources? I used to think to resources as routes containers, but now I’m a bit confused.

Regards, Gabri

I think in general, a resource is the representation of your model and a route is an action or a verb… So in a login Route you do something… you log in. In the posts resource-route, you have records…

Thats the difference I see

/api/posts/ its a resource. you index alot of records.

/api/posts/new there is additionally an action route to the resource route, because you do something… You create a new record.

So it would be like

/api/model/action == /api/comments/new

The only real difference as of 1.7.0 is that resources reset the namespace. A few examples:

Using this.resource

Router.map(function() {
  this.resource('post', { path: '/post/:post_id' }, function() {
    this.route('edit');
    this.resource('comments', function() {
      this.route('new');
    });
  });
});

Will result in looking for the following files (assuming ember-cli layout):

// posts
app/route/posts.js
app/route/posts/index.js
app/templates/posts.hbs
app/templates/posts/index.hbs

// edit
app/route/posts/edit.js
app/templates/posts/edit.hbs

// comments
app/route/comments.js
app/route/comments/index.js
app/templates/comments.hbs
app/templates/comments/index.hbs

// new
app/route/comments/new.js
app/templates/comments/new.hbs

Note that the comments resource is not nested under posts (this is what I mean when I say the namespace is “reset”).

Using this.route

Router.map(function() {
  this.route('post', { path: '/post/:post_id' }, function() {
    this.route('edit');
    this.route('comments', function() {
      this.route('new');
    });
  });
});

Will result in looking for the following files (assuming ember-cli layout):

// posts
app/route/posts.js
app/route/posts/index.js
app/templates/posts.hbs
app/templates/posts/index.hbs

// edit
app/route/posts/edit.js
app/templates/posts/edit.hbs

// comments
app/route/posts/comments.js
app/route/posts/comments/index.js
app/templates/posts/comments.hbs
app/templates/posts/comments/index.hbs

// new
app/route/posts/comments/new.js
app/templates/posts/comments/new.hbs

Note that the comments route is nested under posts.

4 Likes

Good breakdown. Is there a real reason to use one or the other, or is it mostly organizational preference?

I believe over the long term, this.resource will be deprecated, but it will obviously be supported for quite a while.