hhff
hhff

Reputation: 68

Ember.js / Rails Nested JSON

I'm working on a basic Ember / Rails app that has a bunch of nested relationships, for example:

class Release < ActiveRecord::Base
  has_many :tracks
end

When I hit my Releases endpoint, I'm getting some lovely JSON like this:

{
  releases: [{
    id: 1,
    name: "Release Name",
    artist: "Artist Name",
    tracks: [{
      id: 1,
      name: "Track 1",
    },
    {
      id: 2,
      name: "Track 2",
    }]
  }]
}

I've read almost everything I can find on the web about this. How do I map the "Track" model to Ember, so I can display a release with its tracks at the same time?

DS.hasMany? asyc:true? embedded:true? None of this works for me.

Versions:

Upvotes: 2

Views: 522

Answers (1)

Laurie Young
Laurie Young

Reputation: 138414

The following works for me using Active Model Serializer and DS.RESTAdapter

Rails User Model:

class User < ActiveRecord::Base
  has_many :photos
end

Rails User Serializer:

class UserSerializer < ActiveModel::Serializer
  attributes :id, :name
  has_many :photos, embed: :ids, key: "photos", include: true
end

(The magic bit the arguments for has_many. That means they get added them as a second array rather than an embedded array, it also sets the title for the association to be photos which is what Ember requires by default)

This makes Rails return JSON that looks like:

{
  user: {
    id: 1,
    name: "Joe Bloggs",
    photos: [1,2]
  },
  photos: [
    {
      id: 1,
      imageSrc: "/photo1.jpg"
    },
    {
      id: 2,
      imageSrc: "/photo2.jpg"
    }
  ],
}

Then in Ember I define the user model like this:

App.User = DS.Model.extend({
  photos: DS.hasMany('photo'),
  name: DS.attr("string")
});

Finally I define a route that loads the user model:

App.UserShowRoute = Ember.Route.extend({
    model: function(params){
    return this.store.find('user', params.user_id);
  }
});

Upvotes: 1

Related Questions