簡體   English   中英

Ember.js屬於選擇關系中的創建/編輯選擇元素(下拉列表)

[英]Ember.js belongsTo relationship create/edit in select element (dropdown)

我正在嘗試使用下拉菜單設置belongsTo關系。

所以我有我的書籍模型:

import DS from 'ember-data';

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

和我的作者模型:

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 app@model: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)

我想我需要做一些事情,例如讓author對象和將book.author設置為該對象,但是我找不到關於它的清晰解釋。 特別是因為我什至無法弄清楚如何從路線中的選擇菜單中獲取數據!

我覺得我在這里錯過了一些簡單的事情,任何人都有見識?

我建議將此功能移到它所屬的controller.js中。 為什么您與AuthorModel中的書的關系稱為author而不是books 我建議將您的操作(在控制器中)重寫為類似以下內容:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM