0
votes

I've setup my application to work with accepts_nested_attributes_for by doing the following in a serializer:

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'}

This works fine for existing records.

However when I have a new record it doesn't work as expected. In the Ember inspector I end up with 2 foo objects both with the same id for the record created by Rails. One has the unsaved value objects all with a null id the other has the saved value objects with their appropriate id.

Is there a better/more correct way to do this?

Edit:

I realised there was an issue with the JSON coming back from Rails due to the Serializer I was using, I changed that and now only have one record, however it still isn't populating the values association with the correct objects. Those Value objects do exist in the Ember inspector but the association on the Foo object just shows the unsaved records.

Here is a snippet from the JSON response:

{
    "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]}
}

There are some more objects in the JSON (for the options a value is associated to) but as I say the Value objects are populated fine in the inspector, just not associated with the updated Foo record.

Also if I go into the ember inspector for a value and click on it's foo relationship I get this error:

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

1 Answers

0
votes

It turns out I needed to change embedded: 'always' to the following:

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

Because my Rails serializer was giving the ids in the response.