2

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:

  • Ember: 1.4.0-beta.1+canary.011b67b8
  • Ember Data: 1.0.0-beta.5+canary.d9ce2a53
  • Handlebars: 1.1.1
  • jQuery: 1.10.2
2
  • which adapter are you using? Commented Dec 29, 2013 at 20:23
  • I'm on DS.ActiveModelAdapter Commented Dec 30, 2013 at 4:54

1 Answer 1

1

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);
  }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Nailed it! Thanks Laurie - I actually figured this out a couple days ago but haven't had the time to update my post! "embed: :ids, key: "photos", include: true" is the kicker!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.