【问题标题】:Ember.js belongsTo relationship create/edit in select element (dropdown)Ember.js belongsTo 关系在选择元素中创建/编辑(下拉)
【发布时间】:2017-01-07 19:20:27
【问题描述】:

我正在尝试使用下拉菜单设置 belongsTo 关系。

所以我有我的 Books 模型:

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>

如果我删除选择元素并只保存书名,它可以正常工作,但有了它我会得到:(其中 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 设置为此,但我找不到一个明确的解释。尤其是我什至不知道如何从路线中的选择菜单中获取数据!

我觉得我在这里遗漏了一些非常简单的东西,有人有任何见解吗?

【问题讨论】:

    标签: javascript html ember.js handlebars.js


    【解决方案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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2019-08-09
      • 1970-01-01
      • 2021-04-28
      相关资源
      最近更新 更多