要扩展 Sameer 所说的内容,您需要发送 child_attributes 而不是 child。这意味着您不能使用相同的映射从服务器拉取然后推送到它。
在 RestKit 中,您可以指定与原始对象映射不同的自定义序列化。这是一个发布到 Rails 应用程序的示例,其中 Object has_many Images
//Map Images
RKManagedObjectMapping* imageMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Image"];
imageMapping.setNilForMissingRelationships = YES;
imageMapping.primaryKeyAttribute = @"imageId";
[imageMapping mapKeyPathsToAttributes:@"id", @"imageId", @"is_thumbnail", @"isThumbnail", @"image_caption", @"imageCaption", @"image_data", @"imageData", nil];
//Serialize Images
RKManagedObjectMapping* imageSerialization = (RKManagedObjectMapping*)[imageMapping inverseMapping];
imageSerialization.rootKeyPath = @"image";
[imageSerialization removeMappingForKeyPath:@"imageId"];
//Map Objects
RKManagedObjectMapping* objectMapping = [RKManagedObjectMapping mappingForEntityWithName:@"Object"];
objectMapping.setNilForMissingRelationships = YES;
objectMapping.primaryKeyAttribute = @"objectId";
[objectMapping mapKeyPath:@"id" toAttribute:@"objectId"];
[objectMapping mapRelationship:@"images" withMapping:imageMapping];
//Serialize Objects
RKManagedObjectMapping* objectSerialization = (RKManagedObjectMapping*)[objectMapping inverseMapping];
objectSerialization.rootKeyPath = @"object";
[objectSerialization removeMappingForKeyPath:@"images"];
[objectSerialization removeMappingForKeyPath:@"objectId"];
[objectSerialization mapKeyPath:@"images" toRelationship:@"images_attributes" withMapping:imageSerialization];
[objectManager.mappingProvider setMapping:objectMapping forKeyPath:@"object"];
[objectManager.mappingProvider setSerializationMapping:objectSerialization forClass:[Object class]];
请注意,在发帖时删除 ID 属性也很重要——这给我带来了无穷无尽的麻烦,因为它似乎在帖子中并不重要,但它会引发障碍。
值得一提的是,我在使用 rails 解析嵌套对象时也遇到了问题,并且不得不将我的控制器更改为如下所示:
def create
images = params[:object].delete("images_attributes");
@object = Object.new(params[:object])
result = @object.save
if images
images.each do |image|
image.delete(:id)
@object.images.create(image)
end
end
respond_to do |format|
if result
format.html { redirect_to(@object, :notice => 'Object was successfully created.') }
format.json { render :json => @object, :status => :created, :location => @object }
else
format.html { render :action => "new" }
format.json { render :json => @object.errors, :status => :unprocessable_entity }
end
end
end
这可以(并且可能应该)移到对象模型上的 before_create 过滤器中。
我希望这在某种程度上有所帮助。