0
votes

I'm still learning Ember and I'd like some help to solve this problem...

I have a simple library app with authors and books. I'd like to add an "add book" link to my author view template And I want this link to render a new book template, with the book.author defined. But I want it to be displayed in the main outlet

My Models:

App.Author = DS.Model.extend({
    name: DS.attr('string'),
    about: DS.attr('string'),
    picture: DS.attr('string'),
    books: DS.hasMany('book', {async: true})
});

App.Book = DS.Model.extend({
    title: DS.attr('string'),
    isbn: DS.attr('string'),
    summary: DS.attr('string'),
    isAvailable: DS.attr('boolean'),
    featured: DS.attr('boolean'),
    picture: DS.attr('string'),
    author: DS.belongsTo('author', {async: true})
});

Here are my routes:

App.Router.map(function () {

    this.resource('books', function () {
        this.route('edit', {path: '/:book_id/edit'});
        this.route('view', {path: '/:book_id'});
    });

    this.resource('authors', function () {
        this.route('new');
        this.route('edit', {path: '/:author_id/edit'});
        this.route('view', {path: '/:author_id'}, function (){
            this.resource('books', function(){
                this.route('new');
            });
        });
    });
});

URL will be like authors/4/books/new

With this nested routes, I can only display my books.new template inside the authors outlet. I can not display it in the main outlet.


The other way I thought was using thoses routes

App.Router.map(function () {

    this.resource('books', function () {
        this.route('new');
        this.route('edit', {path: '/:book_id/edit'});
        this.route('view', {path: '/:book_id'});
    });

    this.resource('authors', function () {
        this.route('new');
        this.route('edit', {path: '/:author_id/edit'});
        this.route('view', {path: '/:author_id'});
    });
});

and using QueryParams

URL will be like books/new?author_id=4

The template is displayed right, but I could not bind my new book record to its author.

What is the "ember best practice" to make it works?, could you give me an working example?

Thanks.

1
I'd probably change author.view to author.show just to avoid confusion with Ember Views. - Kori John Roys

1 Answers

0
votes

Your nested routes approach is fine, then in your nested books/new controller, add:

needs: ['authors/view'],
author: Ember.computed.alias('controllers.authors.view.model')

then assuming you have a 'save' action on your books/new controller:

save: function() {
  var model = this.get('model');
  var author = this.get('author');
  model.set('author', author);
  model.save().then(...);
}