2011-07-12 16 views
2

私のアプリケーションは、次のモデルクラスがあります。ネストされたJSON要求からレールモデルの作成 - AssociationTypeMismatch

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

マイ:私のコントローラで、私は次のように定義されたcreate方法を、持っている、

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 

ザ・をリクエストはログに次のように表示されます:

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

RestKitを使用する私のiPhoneアプリクライアントから来たアトオングラフ。 私はhereのような他のSOの質問を見てきました、それはthisブログ記事を参照してください。 私の問題は、しかし

Parameters: {"parent"=>{"child_attributes"=>{"grandchild_attributes"=>{"gc_attr1"=>"value1", "gc_attr2"=>"value2"}}, "p_attr1"=>"value1"} 
(デバッガでテスト...それが動作し、そのように)私はこのような要求を構築するためにRestKitを使用して、私のクライアント側からのシリアル化されたグラフを制御する方法がわからないということです

Parent.newメソッドに渡すことができるオプションがあるか、または入れ子になったJSONオブジェクト内でmodel_attributes構造を実現する方法でRestKit JSON出力をカスタマイズすることができますか?

おかげ

+0

をブログ記事には何を言いましたの?リンクは死んでいて、私はObjective Cを話しません! – Chloe

答えて

0

私はビューとしてJSONをレンダリングするために宝石である、RABLを使用してこの問題を解決しました。お見事。 これにより、私のモデルのシリアライゼーショングラフをカスタマイズすることができました。 (OM2.0使用して - 新しいオブジェクトのマッピング)をRestKit側

は、私は、例えば、すべての関係のすべての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"]; 
関連する問題