Ember.js属于选择元素中的关系创建/编辑(下拉列表)

时间:2017-01-07 19:20:28

标签: javascript html ember.js handlebars.js

我正在尝试使用下拉列表设置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)

我认为我需要做一些事情,比如获取作者对象并将book.author设置为,但我无法找到明确的解释。特别是因为我甚至无法弄清楚如何从路线中的选择菜单中获取数据!

我觉得我在这里缺少一些非常简单的东西,任何人都有任何见解?

1 个答案:

答案 0 :(得分:1)

我建议将此功能移至您所属的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);
}