开发者

Creating rails model from nested JSON request - AssociationTypeMismatch

开发者 https://www.devze.com 2023-03-19 07:44 出处:网络
My application has the following model classes: class Parent < ActiveRecord::Base # Setup accessible (or protected) attributes开发者_JAVA技巧 for your model

My application has the following model classes:

class Parent < ActiveRecord::Base
    # Setup accessible (or protected) attributes开发者_JAVA技巧 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

The, in my controller i have a create method, defined as follows:

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

My request is showing up in the logs as:

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

Which is the full serialization graph that came from my iphone app client that uses RestKit. I have seen on other SO questions like here , thats refers to this blog post. My problem, however is that I don't know how to control the serialized graph from my client side using RestKit in order to build a request like this (and that way, it works.. tested with debugger)

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

Anyone have ideas if there is any option I can pass on to the Parent.new method or customize the RestKit JSON output in a way that I may achieve the model_attributes structure within nested JSON objects?

Thanks


I have solved this issue by using RABL, which is a gem to render json as views. Awesome work. This allowed me to customize the serialization graph of my model.

On RestKit side (using OM2.0 - new object mapping), I have changed my mappings all to child_attributes for all relationships, for instance:

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"];
0

精彩评论

暂无评论...
验证码 换一张
取 消