2017-01-07 3 views
0

ドロップダウンを使用してbelongsTo関係を設定しようとしています。Ember.js belongsTo関係select要素での作成/編集

import DS from 'ember-data'; 

export default DS.Model.extend({ 
    // Relationships 
    author: DS.belongsTo('author'), 
    name: DS.attr() 
}); 

そして、私のAuthorモデル::

import DS from 'ember-data'; 

export default DS.Model.extend({ 
    // Relationships 
    author: DS.hasMany('books'), 
    name: DS.attr() 
}); 

マイブック/新ルート:

import Ember from 'ember'; 

export default Ember.Route.extend({ 

    model() { 
    return Ember.RSVP.hash({ 
     book: this.store.createRecord('book'), 
     authors: this.store.findAll('author') 
    }) 
    }, 

    actions: { 

    saveBook(newBook) { 
     newBook.book.save().then(() => this.transitionTo('book')); 

    }, 

    willTransition() { 
     this.controller.get('book').rollbackAttributes(); 
    } 
    } 
}); 

そして、私の本/新しいテンプレート

は、だから私は、私の本のモデルを持っています:

<label >Book Name</label> 
{{input type="text" value=model.name placeholder="Book Name"}} 

<label>Author</label> 
<select> 
    {{#each model.authors as |author|}} 
    <option value="{{author.id}}"> 
     {{author.name}} 
    </option> 
    {{/each}} 
</select> 
<button type="submit"{{action 'saveBook' model}}>Add Book</button> 

私はselect要素を削除し、ちょうどそれが正常に動作ブックの名前を保存し、それを、私はこれを取得した場合:(idは自動生成されたIDです)

Error: Some errors were encountered while saving [email protected]:book id 
at reportError (firebase.js:425) 
at firebase.js:445 
at tryCatch (ember.debug.js:58165) 
at invokeCallback (ember.debug.js:58177) 
at publish (ember.debug.js:58148) 
at publishRejection (ember.debug.js:58091) 
at ember.debug.js:37633 
at invoke (ember.debug.js:339) 
at Queue.flush (ember.debug.js:407) 
at DeferredActionQueues.flush (ember.debug.js:531) 

私は私がする必要があると思います著者オブジェクトを取得してbook.authorを設定するようなことをしてください。しかし、私はどのようにして明確な説明を見つけることができません。特に私は経路の選択メニューからデータを取得する方法を理解することができないので!

私はここでかなり簡単な何かを見逃しているように感じる、誰もが洞察力を持っていますか?

答えて

1

私はこの機能をあなたのcontroller.jsに移すことをお勧めします。 AuthorModelの書籍との関係がbooksの代わりにauthorと表示されるのはなぜですか? 私はこのような何かに(コントローラに)あなたの行動を書き換えることをお勧め:

saveBook(newBook) { 
    newBook.set('author', this.get('selectedAuthor') // or just the call below if you go with the alternative below 
    newBook.save().then(() => this.transitionTo('book')); 

}, 

今の問題は、あなたが選択した作者への結合を持っていないこと、持続します。 ember-power-selectのようなものを使用して、選択した著者をコントローラプロパティにバインドすることをお勧めします。

次に、あなたのテンプレートでこれを行うだろう:

{{#power-select 
    placeholder="Please select Author" 
    onchange=(action "authorSelectionChanged") 
    options=model.authors 
    as |author|}} 
    {{author.name}} 
{{/power-select}} 

そして、あなたのコントローラ内のあなたのactions中:

authorSelectionChanged(author) { 
    this.get('model.book').set('author', author); 
    // or the following if you go with the alternative above 
    this.set('selectedAuthor', author); 
} 
関連する問題