Ember使用accepts_nested_attributes_for创建记录

时间:2014-11-11 16:22:28

标签: ember.js ruby-on-rails-3.2 ember-data

我已通过在序列化程序中执行以下操作来设置我的应用程序以使用accepts_nested_attributes_for:

App.FooSerializer = DS.ActiveModelSerializer.extend DS.EmbeddedRecordsMixin,
    serialize: (record, options) ->
        json = @_super(record, options)

        # re-write the keys for accepts_nested_attributes_for
        json.values_attributes = json.values
        delete json.values

        json

    attrs:
        values: {embedded: 'always'}

这适用于现有记录。

但是,当我有新记录时,它无法按预期工作。在Ember检查器中,我最终得到了2个foo对象,这两个对象具有由Rails创建的记录的相同id。一个具有未保存的值对象全部具有空id,另一个具有保存的值对象及其适当的id。

有更好/更正确的方法吗?

修改

我意识到由于我正在使用的Serializer而从Rails回来的JSON存在问题,我改变了它,现在只有一条记录,但它仍然没有填充与正确对象的值关联。这些Value对象确实存在于Ember检查器中,但Foo对象上的关联只显示未保存的记录。

以下是JSON响应的摘录:

{
    "values": [{"id":19582,"value":"9C5601","foo_id":1158,"option_id":2} ...],
    ""foo": {"id":1158,"value_ids":[19581,19582,19583,19584,19585,19586,19587,19588,19589,19590,19591,19592,19593,19594,19595,19596]}
}

JSON中还有一些对象(对于与值相关联的选项),但正如我所说,Value对象在检查器中填充得很好,只是与更新的Foo记录没有关联。

此外,如果我进入ember检查器获取值并单击它的foo关系,我会收到此错误:

Uncaught Error: Assertion Failed: You looked up the 'foo' relationship on a 'value' with id 19596 but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`) 

1 个答案:

答案 0 :(得分:0)

事实证明我需要将embedded: 'always'更改为以下内容:

values: {
    serialize: 'records',
    deserialize: 'ids'
}

因为我的Rails序列化程序在响应中给出了id。