【问题标题】:How to create record with belongsTo relationship in ember.js如何在 ember.js 中创建具有 belongsTo 关系的记录
【发布时间】:2015-01-21 00:54:07
【问题描述】:

我需要通过选择保存两个模型之间的关系。 我的模型:

`import DS from 'ember-data'`

Animal = DS.Model.extend {
  name: DS.attr 'string'
  nameEng: DS.attr 'string'

  animalType: DS.belongsTo 'animalType'
}

`export default Animal`

`import DS from 'ember-data'`

AnimalType = DS.Model.extend {
  title: DS.attr 'string'

  animals: DS.hasMany('animal')
}
`export default AnimalType`

路线:

AnimalsNewRoute = Ember.Route.extend
  model: -> @store.createRecord 'animal'

控制器:

AnimalsNewController = Ember.ObjectController.extend
  animalTypes: (-> 
    @store.find 'animalType'
  ).property()

  actions:
    createAnimal: ->
      @get('model').save().then (animal) =>
        console.log(animal.id)

我在徽章中的选择:

= view "select" content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"

在服务器上我得到这个 json:

{
  "animal"=>{
              "name"=>"some string", 
              "name_eng"=>"some string", 
              "animal_type_id"=>nil
            }
}

如何设置动物类型?

【问题讨论】:

  • 您使用哪个Adapter?您使用嵌入式记录吗? (我看不到 async: true )。你能设置一个演示吗? emberjs.jsbin.com
  • 我用DS.ActiveModelAdapter

标签: ember.js ember-data


【解决方案1】:

在我看来,您缺少 Em.Select 上的绑定选定值。 你能尝试绑定吗:

view "select" value=model.animalType content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"

【讨论】:

  • 它对我不起作用(我有一个错误Uncaught Error: Assertion Failed: You can only add a 'animalType' record to this relationship
【解决方案2】:

对我来说,这个解决方案有效:

view "select" selection=model.animalType content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"

使用selection 而不是value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-19
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2016-04-26
    • 1970-01-01
    相关资源
    最近更新 更多