2015-04-06 46 views
0

我的問題是「簡單」,但我不能與Ember解決這個問題....Ember路線如何?

這是一個小型圖書館應用程序,與作者和圖書與路線做工精細

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

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

現在我要添加,讓我登記新書的路線,利用從當前作者模板的鏈接/authors/156

路線必須打開一個books/new模板,並與他author鏈接new book對象:即我想顯示<h1>New book from {{author.name}}</h1>

我應該添加哪些路線到現有路線? 如何將作者參考傳遞給新書對象?

回答

0

我看到這樣做的方式有三種:

  1. 把它放在books資源下,並要求筆者爲路由參數:

    this.resource('books', function() { 
        this.route('new', { path: '/new/:author_id' }); 
    }); 
    
  2. books資源下的路線,但請將作者改爲query parameter

    this.resource('books', function() { 
        // Declare required query parameter on controller for `new` route 
        this.route('new'); 
    }); 
    
  3. 把路線authors下,需要筆者在URL:

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

我建議第三個選項,因爲我認爲這是最乾淨的。在你的控制器,你可以很容易地創建一本新書:

export default Ember.Controller.extend({ 
    actions: { 
     createBook: function() { 
      var author = this.get('model'); 
      var book = this.store.createRecord('book', { 
       author: author, 
       ... 
      }); 

      book.save(); 
     } 
    } 
}); 
+0

首先,感謝這個答案。也許我錯了,但我不喜歡創建'author.newbook route'的想法。我更喜歡'book.new'。我正在嘗試第一個選項'book/new /:author_id',但是現在我又陷入了另一個問題:如何將新書鏈接到作者。我認爲它必須在'BookNewRoute'內完成,'model:function(){return this.store.createRecord('book')}'但是怎麼做? –

0

我試過了,併成功地使用了第二個建議的方法,查詢參數。

路由器:

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

路線

App.BooksNewRoute = Ember.Route.extend({ 
    queryParams: { 
     author_id: { 
      refreshModel: true 
     } 
    }, 
    model: function (params) { 
     var newBook = this.store.createRecord('book'); 
     this.store.find('author', params.author_id).then(function (author) { 
      newBook.set('author', author); 
     }); 
     return newBook; 
    } 
}); 

和控制所有的

App.BooksNewController = Ember.ObjectController.extend({ 
    queryParams: ['author_id'], 
    author_id: null, 
    actions: { 
     save: function() { 
      var controller = this; 
      this.get('model').save().then(function (book) { 
       controller.transitionToRoute('books.show', book); 
      }, function (error) { 
       console.error(error); 
      }); 
     }, 
     cancel: function() { 
      this.get('model').rollback(); 
      this.transitionToRoute('index'); 
     } 
    } 
});