문제

I have the following scenario: I have a rails web portal (Rails 3.1) and I use RestKit 0.9.3 (the newest version) to connect the the portal from an iOS device. I want to map the data structure from the server to the core data model on the iOS device. The model is designed as follows:

Classes

  • User
  • Role
  • Post
  • Comment

Relations

  • A User has zero or one Role / A Role can have multiple Users
  • A User has multiple Posts / A Post has one User
  • A Post has multiple Comments / A Comment has one Post

The problem is, that the default mapping of relations in RestKit results in huge messages and redundant transfer because when I send/recieve the Roles, all the Users will be transfered as well and if I send/recieve the Users, the Role is added to each User. The same occurs with Users, Posts and Comments. It's just to much data and the best solution, as far as I could think of one, is to just send the IDs, which are referenced and transfer each type. This works perfectly when I send the data from the iOS device to the server by mapping the IDs of the Role to a field "role_id" in the User, because Rails does understand what to do with that. So the relations are not mapped as relations but just as ID fields. But when I receive Users from the server, which where not present on the device, I get an error, because RestKit does not understand what to do with the mapping, since there is no Role object linked to the User object.

So I researched and found out that you can map the relations and use a mapping of the primary key, so that RestKit would only send the Primary Key of the Role. But now Rails does not understand what to do with it. It looks something like this:

{ "id":1, "uid":"my_user_name", "pwd":"my_password", "role": { "id":0 } }

But Rails is expecting something like that:

{ "id":1, "uid":"my_user_name"; "pwd":"my_password", "role_id":0 }

That's my current state and I really don't know how to solve this misunderstandings.

I would be very thankful for any help!

도움이 되었습니까?

해결책

There are two possible solutions for that:

1) Make your rails model aware of the fact that you want to mass update the role-relationship by adding

accepts_nested_attributes_for :role

or

2) Change the serialization mapping of your client code.

RKObjectMapping *userMapping = [RKObjectMapping mappingForClass:[User class]];
[userMapping mapKeyPath:@"id" toAttribute:@"userId"];
[userMapping mapKeyPath:@"uid" toAttribute:@"uid"];

...

[manager.mappingProvider registerMapping:userMapping withRootKeyPath:@"user"];

RKObjectMapping* userSerializationMapping = [manager.mappingProvider serializationMappingForClass:[User class]];
[userSerializationMapping mapKeyPath:@"role_id" toAttribute:@"role.id"];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top