2

私のアプリケーションには、次のモデル クラスがあります。

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"}

これは、RestKit を使用する iPhone アプリ クライアントから取得した完全なシリアライゼーション グラフです。hereのような他のSOの質問を見てきました。これは、このブログ投稿を参照しています。しかし、私の問題は、このようなリクエストを作成するためにRestKitを使用してクライアント側からシリアル化されたグラフを制御する方法がわからないことです(そのように動作します..デバッガでテストされています)

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

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

ありがとう

4

1 に答える 1

0

json をビューとしてレンダリングする宝石であるRABLを使用して、この問題を解決しました。お見事。これにより、モデルのシリアル化グラフをカスタマイズできました。

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"];
于 2011-07-14T06:08:58.410 に答える