简体   繁体   English

Ember.js / Rails嵌套JSON

[英]Ember.js / Rails Nested JSON

I'm working on a basic Ember / Rails app that has a bunch of nested relationships, for example: 我正在开发一个基本的Ember / Rails应用程序,该应用程序具有很多嵌套关系,例如:

class Release < ActiveRecord::Base
  has_many :tracks
end

When I hit my Releases endpoint, I'm getting some lovely JSON like this: 当我点击Releases端点时,我得到了一些可爱的JSON,如下所示:

{
  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? 如何将“ Track”模型映射到Ember,以便同时显示带有其轨道的发行版?

DS.hasMany ? DS.hasMany吗? asyc:true ? asyc:true吗? embedded:true ? embedded:true吗? None of this works for me. 这些都不适合我。

Versions: 版本:

  • Ember: 1.4.0-beta.1+canary.011b67b8 灰烬:1.4.0-beta.1 + canary.011b67b8
  • Ember Data: 1.0.0-beta.5+canary.d9ce2a53 灰烬数据:1.0.0-beta.5 + canary.d9ce2a53
  • Handlebars: 1.1.1 车把:1.1.1
  • jQuery: 1.10.2 的jQuery:1.10.2

The following works for me using Active Model Serializer and DS.RESTAdapter 以下使用Active Model SerializerDS.RESTAdapter为我工作

Rails User Model: Rails用户模型:

class User < ActiveRecord::Base
  has_many :photos
end

Rails User Serializer: Rails用户序列化器:

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) (神奇之处在于has_many的参数。这意味着它们被添加为第二个数组而不是嵌入式数组,并且还将关联的标题设置为photos ,这是Ember默认需要的)

This makes Rails return JSON that looks like: 这使Rails返回如下所示的JSON:

{
  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: 然后在Ember中,我定义用户模型如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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