How is ember-data's support for loading embedded associations?


#1

Using Ember Data : 1.0.0-beta.4

I’m working on my first ember app using a rails backend and activerecord serializers to generate JSON data for ember to use. My question is, how is ember’s support for embedded has_many relationships?

For example, I would like to write a serializer like this

class RegistrySerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :categories
end

Any my Ember models like this

App.Registry = DS.Model.extend
  name: DS.attr('string')
  categories: DS.hasMany('Category', { embedded: 'always' })

App.Category = DS.Model.extend
  name: DS.attr('string')
  registry: DS.belongsTo('Registry')

#2

@bemathis the DS.EmbeddedRecordsMixin has good support for embedded ‘hasMany’ relationships, see the source code for more info: https://github.com/emberjs/data/blob/v1.0.0-beta.6/packages/activemodel-adapter/lib/system/embedded_records_mixin.js


#3

Your serializer can be instructed to include the items you want when the request is made.

class RegistrySerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :categories
  embed :ids, include: true
end

There are some issues with the naming in your Ember models, for example the capitalization isn’t necessary. I’m also not sure that the { embedded: 'always' } is necessary.

App.Registry = DS.Model.extend
  name: DS.attr('string')
  categories: DS.hasMany('category')

App.Category = DS.Model.extend
  name: DS.attr('string')
  registry: DS.belongsTo('registry')

How are you setting up your store? For example are you using the ActiveModelAdapter? The sample below will tell Ember how to interact with data from ActiveModelSerializers. By reopening the RESTAdapter and suppling the namespace this will be prepended to the request URL. In the example below getting your Registry index would hit api/v1/registrys

App.Store = DS.Store.extend({
    adapter: '-active-model'
});

App.RESTAdapter.reopen(
    {namespace: "api/v1"}
);

Hope this helps.


#4

I’m using the ActiveModelAdaptor in my store.coffee file

App.ApplicationAdapter = DS.ActiveModelAdapter.extend
  namespace: 'api/v1'

I’ve managed to get Ember reading associations properly by doing what you suggested and telling my Serializer to embed the ids

class RegistrySerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :name

  has_many :categories
end

I do find what you said about the store configs interesting thought. Would something like that be needed w/my current store setup? Is you config generally preferable over using ActiveModelAdapter which I am to useing the 1.0.0.beta7 of.


#5

I think what you’re doing is fine. I can’t even remember where I picked up that configuration style! I haven’t found it to be a problem, so just kept using it. Having said that the syntax you’ve used is perfectly valid and more succinct!

If it’s not causing any problems, why change :smile: