2012-10-23 36 views
1

我在hasMany鏈中有3個模型。 E.G.圖庫 - >圖片 - >評論如何避免缺少2級深度關聯映射?

返回所選的圖庫和它在單個json響應中的圖像按預期工作。後端是一個Rails應用程序,使用active_model_serializers,順便說一句。

{"images":[...],"galleries":{"id":1,...,"images":[1,2,3]}} 

但是,當我告訴串行器關於評論,他們得到包括在JSON中我從Ember得到一個映射錯誤。

{"comments":[...],"images":[...],"galleries":{"id":1,...,"images":[1,2,3]}} 

Error: assertion failed: Your server returned a hash with the key comments but you have no mapping for it

我無法弄清楚如何正確地告訴灰燼如何處理這個問題。我的調試表明,json響應中的任何內容都必須在Gallery模型中直接引用。我曾嘗試使用單數和複數形式向RESTAdapter添加「映射」,以確保它的正確性。 「評論:App.Comment」或「評論:App.Comment」沒有什麼區別,我可以看到。

我想我可以放棄,只是做更多的請求,但由於評論總是在使用給定的圖像時使用,所以感覺不對。我希望能夠幫助我們確定如何在單一響應中允許數據。

我是否需要完全重新配置序列化程序和Ember以嵌入數據而不是使用ID引用它們?

chers, 馬丁

(注:型號名稱是虛構的,使他們更普遍理解相比樂趣域我實際上建模)

+0

在我的應用程序,我做這樣的事情 商店= DS.Store.extend({ 適配器:DS.RESTAdapter.create({ 串行:DS.RESTSerializer, bulkCommit:假的, 映射:{ action_words:ActionWord } }) })和它的工作原理:s –

+0

我到目前爲止所做的工作是更改json以使註釋嵌入到圖像中。它使網絡喋喋不休,但比我想要的更少。 –

+0

您是否找到解決您的問題的方法?我有同樣的問題,Ember對json的格式非常嚴格,我不能很容易地改變我的後端(Symfony)... –

回答

2

感謝捅了捅我要回這個。

這是我目前的。我不知道是否可以刪除Ember和Ember Data的最新更新。

的商店規定:

DS.RESTAdapter.configure("plurals", { 
    image: 'images', 
    gallery: 'galleries', 
    comment: 'comments' 
}); 
DS.RESTAdapter.configure('App.Image', { 
    sideloadAs: 'images' 
}); 
DS.RESTAdapter.configure('App.Comment', { 
    sideloadAs: 'comments' 
}); 
App.store = DS.Store.create({ 
    revision: 11, 
    adapter: DS.RESTAdapter.create({ 
    mappings: { 
     comments: 'App.Comment' 
    } 
    }) 
}); 

我相當肯定,如果你的數據是一樣的圖像和正常的事情,你的話不需要複數的定義。我的域名在概念上接近於這些,但更具技術性。我選擇使用這些名稱發佈,以使概念和關係更易於理解。

我的模型包含以下......所有其他常用的東西。

App.Gallery = DS.Model.extend({ 
    images: DS.hasMany('App.Image',{key: 'images', embbeded: true}) 
}); 

App.Image = DS.Model.extend({ 
    comments: DS.hasMany('App.Comment',{key: 'comments', embedded: true}), 
    gallery: DS.belongsTo('App.Gallery') 
}); 

App.Comment = DS.Model.extend({ 
    image: DS.belongsTo('App.Image') 
}); 

這讓我返回的JSON結構像一個在我的問題:

{"comments":[...],"images":[...],"galleries":{"id":1,...,"images":[1,2,3]}} 

這是使用Rails的ActiveModelSerializers產生。我的串行器看起來像這樣:

class ApplicationSerializer < ActiveModel::Serializer 
    embed :ids, :include => true 
end 
class GallerySerializer < ApplicationSerializer 
    attributes :id, ... 
    root "gallery" 
    has_many :images, key: :images, root: :images 
end 
class ImageSerializer < ApplicationSerializer 
    attributes :id, ... 
    root "image" 
    has_many :comments, key: :comments, root: :comments 
end 
class CommentSerializer < ApplicationSerializer 
    attributes :id, ... 
end 

再次。我認爲你可以遠離不那麼冗長。我的導軌模型不是簡單的稱爲「圖庫」。他們的名字間隔如「BlogGallery」,但我不希望Ember必須處理所有這些。我需要東西出於這個原因。

我認爲涵蓋了所有關於關聯的內容並將它們嵌入到相同的json響應中。