如何在 ember.js 中创建具有 belongsTo 关系的记录
How to create record with belongsTo relationship in ember.js
我需要通过 select 保存两个模型之间的关系。
我的模特:
`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)
还有我的select徽章:
= view "select" content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"
在服务器上我得到这个 json:
{
"animal"=>{
"name"=>"some string",
"name_eng"=>"some string",
"animal_type_id"=>nil
}
}
如何设置动物类型?
在我看来,您在 Em.Select 上缺少绑定所选值。
您能否尝试绑定:
view "select" value=model.animalType content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"
对我来说,这个解决方案有效:
view "select" selection=model.animalType content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"
使用 selection
而不是 value
。
我需要通过 select 保存两个模型之间的关系。 我的模特:
`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)
还有我的select徽章:
= view "select" content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"
在服务器上我得到这个 json:
{
"animal"=>{
"name"=>"some string",
"name_eng"=>"some string",
"animal_type_id"=>nil
}
}
如何设置动物类型?
在我看来,您在 Em.Select 上缺少绑定所选值。 您能否尝试绑定:
view "select" value=model.animalType content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"
对我来说,这个解决方案有效:
view "select" selection=model.animalType content=animalTypes optionValuePath="content.id" optionLabelPath="content.title"
使用 selection
而不是 value
。