简体   繁体   中英

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:

  • 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

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);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM