2011-07-12 32 views
2

我的應用程序具有以下模型類:創建軌道從嵌套JSON請求模型 - AssociationTypeMismatch

class Parent < ActiveRecord::Base 
    # Setup accessible (or protected) attributes for your model 
    attr_accessible :child_attributes, :child 

    has_one :child 

    accepts_nested_attributes_for :child 

    #This is to generate a full JSON graph when serializing 
    def as_json(options = {}) 
     super(options.merge, :include => {:child => {:include => :grandchild } }) 
    end 
end 

class Child < ActiveRecord::Base 
    # Setup accessible (or protected) attributes for your model 
    attr_accessible :grandchild_attributes, :grandchild 

    belongs_to :parent 
    has_one :grandchild 

    accepts_nested_attributes_for :grandchild 
end 

class Grandchild < ActiveRecord::Base 
    belongs_to :child 
end 

的,在我的控制器我有一個create方法,定義如下:

def create 
    @parent = Parent.new(params[:parent]) 
    #Rest ommited for brevity - just respond_with and save code 
    end 
end 

我請求顯示在日誌中:

Parameters: {"parent"=>{"child"=>{"grandchild"=>{"gc_attr1"=>"value1", "gc_attr2"=>"value2"}}, "p_attr1"=>"value1"} 

這是完整的serializ圖表來自我的iPhone應用程序客戶端,使用RestKit。 我已經看到其他SO問題,如here,這是指this博客文章。 我的問題,不過是,我不知道如何控制從以建立這樣的請求,利用RestKit我的客戶端上的序列圖(和這樣一來,它的工作原理。與調試測試)

Parameters: {"parent"=>{"child_attributes"=>{"grandchild_attributes"=>{"gc_attr1"=>"value1", "gc_attr2"=>"value2"}}, "p_attr1"=>"value1"} 

如果有任何選項可以傳遞給Parent.new方法,或者以可以在嵌套的JSON對象內實現model_attributes結構的方式自定義RestKit JSON輸出,任何人都有想法嗎?

感謝

+0

什麼做的博客文章說?鏈接已經死了,我不說目標C! – Chloe

回答

0

我以RABL,這是一個寶石呈現JSON作爲意見解決了這個問題。令人敬畏的工作。 這使我可以自定義我的模型的序列化圖。

在RestKit端(使用OM2.0 - 新的對象映射),我已經改變了我的映射所有child_attributes的所有關係,例如:

RKObjectMapping* parentMapping = ... //Initialize your mapping here 
RKObjectMapping* childMapping = ... //Initialize your mapping here 

//Configure mapping relationship with child 
[parentMapping mapKeyPath:@"child_attributes" toRelationship:@"childProperty" withObjectMapping:childMapping]; 

//Register mappings 
RKObjectManager* manager = [RKObjectManager sharedManager]; 
[manager.mappingProvider registerMapping:parentMapping withRootKeyPath:@"parent"]; 
[manager.mappingProvider registerMapping:childMapping withRootKeyPath:@"child"];