那麼,在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設計的破解者。如果有人知道一個簡單的方法或可能做一些嵌入式(總是或加載在適配器,我不明白),請評論:)
我有一種感覺,這是類似的問題https:// github.com/emberjs/data/pull/695 – 2013-04-29 20:41:41