1

使用燼數據,我有這兩種型號:如何在多個關聯中填充相關模型?

App.Post = DS.Model.extend 
    title: DS.attr "string" 
    body: DS.attr "string" 
    categories: DS.hasMany "App.Category" 

App.Category = DS.Model.extend 
    name: DS.attr "string" 
    posts: DS.hasMany 'App.Post' 

這系列化:

class PostSerializer < ActiveModel::Serializer 
    attributes :id, :title, :body 

    has_many :categories 
    embed :ids, include: true 
end 

class CategorySerializer < ActiveModel::Serializer 
    attributes :id, :name 
end 

當我問的帖子,我得到預期的JSON,我可以訪問後的類別不問題,但如果我請求類別(我認爲他們被緩存),我得到與職位沒有任何關係的類別。它甚至不嘗試做出請求(這也不起作用)。

那麼,不應該將類別的帖子關係填滿嗎?

不知道如果我錯過燼或AMS(我認爲該類別串行應該知道,有很多文章)的東西

+0

我有一種感覺,這是類似的問題https:// github.com/emberjs/data/pull/695 – 2013-04-29 20:41:41

回答

2

那麼,在IRC有些人掙扎後,我用這個解決方案,結束了我希望這會對其他人有所幫助,並可能有所改進。

問題在於這些類別沒有任何後期參考,因此如果您要求發佈帖子,您將獲得具有類別的帖子,但類別本身對帖子一無所知。

如果我嘗試做這樣的事情:

class CategorySerializer < ActiveModel::Serializer 
    attributes :id, :name 

    has_many :posts 
    embed :ids, include: true 
end 

它會爆炸,因爲它們在引用對方,你會得到一個「太多深層次」或類似的東西。

你可以這樣做:

class CategorySerializer < ActiveModel::Serializer 
    attributes :id, :name 

    has_many :posts, embed: :objects 
end 

,它會工作,但因爲當你申請的職位,你會得到每一個崗位+每一個註釋,在他們裏面,有每一個崗位,結果JSON將是巨大的該類別...沒有愛

那麼有什麼想法?有了這樣的:

class PostSerializer < ActiveModel::Serializer 
    attributes :id, :title, :body 

    has_many :categories 
    embed :ids, include: true 
end 

class CategorySerializer < ActiveModel::Serializer 
    attributes :id, :name 

    has_many :posts, embed: :ids 
end 

對於每一個崗位你得到categories_ids和每次引用類,你只能得到它的屬性和屬於該類別的帖子的ID(不是整個對象)。

但是當你轉到'/#/ categories'並且你還沒有加載帖子時會發生什麼?那麼,因爲你的CategorySerializer沒有序列化任何帖子,你什麼也得不到。

所以既然你不能做串行器之間的交叉引用,我結束了4個序列化器。 2員額和其類別和2個類別和崗位(所以,不,如果你第一次加載的職位或類別的問題):

class PostSerializer < ActiveModel::Serializer 
    attributes :id, :title, :body 

    has_many :categories, serializer: CategoriesForPostSerializer 
    embed :ids, include: true 
end 

class CategoriesForPostSerializer < ActiveModel::Serializer 
    attributes :id, :name 

    has_many :posts, embed: :ids 
end 

class CategorySerializer < ActiveModel::Serializer 
    attributes :id, :name 

    has_many :posts, serializer: PostsForCategorySerializer 
    embed :ids, include: true 
end 

class PostsForCategorySerializer < ActiveModel::Serializer 
    attributes :id, :title, :body 

    has_many :categories, embed: :ids 
end 

該做的伎倆。但是因爲我是Ember的新手,我不是JSON設計的破解者。如果有人知道一個簡單的方法或可能做一些嵌入式(總是或加載在適配器,我不明白),請評論:)