I'm developing a CoreData iOS app that's backed by a (Rails) REST API (that supports shallow routes). Because there are a lot of objects in the graph, I'd like the REST GETs to not to include a lot of nested results and, instead, just contain references that RestKit uses to establish (faulted) relationships. I'll then use shallow routes to request the individual (or groups of) objects as needed.
Assuming I have a one-to-many (<-->>) data model such as A <-->> B, I have:
RKEntityMapping *a_mapping = [RKEntityMapping mappingForEntityForName:@"A" inManagedObjectStore:managedObjectStore];
[a_mapping addAttributeMappingsFromDictionary:@{@"a_id" : @"aId", ...}];
a_mapping.identificationAttributes = @[@"aId"];
RKEntityMapping *b_mapping = [RKEntityMapping mappingForEntityForName:@"B" inManagedObjectStore:managedObjectStore];
[b_mapping addAttributeMappingsFromDictionary:@{@"b_id" : @"bId", ...}];
b_mapping.identificationAttributes = @[@"bId"];
[a_mapping addPropertyMapping:[RKRelationshipMapping relationshipMappingFromKeyPath:@"bs" toKeyPath:@"bs" withMapping:b_mapping]];
I have these routes:
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *a_ResponseDescriptor;
a_ResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:a_mapping method:RKRequestMethodGET pathPattern:@"/A/:aId" keyPath:@"A" statusCodes:statusCodes];
RKResponseDescriptor *b_ResponseDescriptor;
NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
b_ResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:b_mapping method:RKRequestMethodGET pathPattern:@"/B/:bId" keyPath:@"B" statusCodes:statusCodes];
[[RKObjectManager sharedManager] addResponseDescriptor:a_ResponseDescriptor];
[[RKObjectManager sharedManager] addResponseDescriptor:b_ResponseDescriptor];
I have a couple of related questions:
How should I structure the JSON when returning an 'A' record so that RestKit will instantiate stubs for any related 'B' objects?
Similarly, if I want to request a bunch of B objects (without prior knowledge of A objects) how do I structure the JSON when returning a 'B' record so that RestKit will instantiate stubs for the owning 'A' object?
What additional setup/code do I need with RestKit?
Currently, I have one direction working (A --> B), but I can't seem to figure out how to get the reverse to work. In particular, /A/1.json returns something like:
{"a": {"a_id":1, "bs":[{"b_id": 2}, {"b_id": 3}]}}
And B/2.json returns:
{"b": {"b_id":2, "a_id": 1}}
Should I instead be using something like:
{"b": {"b_id":2, "a": {"a_id": 1}}}
? Any help/advice would be appreciated.