jspooner
jspooner

Reputation: 11315

RestKit mapping with Rails 3.1

In Rails 3.0.8 the json contains a root element with your model name. For example my Location model.

[
{
location: {
city: San Diego
name: Mission Valley YMCA Krause Family Skatepark
pads_required: 0
country: United States

And the mapping provider looked directly for the location object.

RKObjectMapping* locationMapping = [RKObjectMapping mappingForClass:[RKLocation class]];   
[locationMapping mapKeyPath:@"id" toAttribute:@"locationId"];
...
[objectManager.mappingProvider setMapping:locationMapping forKeyPath:@"location"];

Now when you upgrade to rails 3.1.0 the root node "location" is now removed by default and I'm not sure how to configure the mapping provider without it? I tried nil and looked for alternative methods but was unsuccessful.

Do you know how to map this? Please help!

[
{
   city: San Diego
   name: Mission Valley YMCA Krause Family Skatepark
   pads_required: 0
   country: United States

Upvotes: 8

Views: 1561

Answers (3)

Simon Woodside
Simon Woodside

Reputation: 7314

Short and sweet answer: forKeyPath:@"" will work.

Upvotes: 0

tassock
tassock

Reputation: 1653

In RestKit, you can register a mapping to contain a root model name like this:

[objectManager.mappingProvider registerMapping:locationMapping withRootKeyPath:@"location"];

Upvotes: 4

Evan Cordell
Evan Cordell

Reputation: 4118

From the RestKit side, I don't know, but from this topic it looks like you can get the json back to what RestKit expects by doing:

class Location < ActiveRecord::Base
  self.include_root_in_json = true
end

Edit: For completeness, here's how you'd do it with RestKit:

RKObjectMapping* locationMapping = [RKObjectMapping mappingForClass:[RKLocation class]];   
[locationMapping mapKeyPath:@"id" toAttribute:@"locationId"];
...
[objectManager.mappingProvider addObjectMapping:locationMapping];

And then calling the mapper later:

RKObjectMapping* locationMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[RKLocation class]];
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/locations" objectMapping:locationMapping delegate:self];

And then you'd handle the objects in RKObjectLoader delegate methods.

Upvotes: 7

Related Questions