11

I have two Core Data entities (Client and UserFile) that I have successfully set up a relationship between.

I have created classes for both entities, and made them subclasses of RKManagedObject.

When I create a new UserFile, I want to correctly associate it with a Client. Here's what I'm doing:

Client *client = [Client objectWithPrimaryKeyValue:@"1"];
UserFile *file = [UserFile object];
file.client = client;
file.clientId = client.clientId;
[[RKObjectManager sharedManager] postObject:file delegate:self];

It seems like I have to assign file.clientId so that the correct parameter is sent to the server (if I only assign file.client then the submitted client_id is blank).

It seems like I have to assign file.client to prevent a new, empty Client from being created and associated with the file (the client relationship is required).

Is this correct? Do I really have to assign both the foreign key and the actual entity? This seems a bit redundant to me, but I'll happily admit that my Core Data and RestKit knowledge is lacking!

akpb
  • 301
  • 1
  • 4
  • 19
nfm
  • 19,689
  • 15
  • 60
  • 90
  • could you maybe post edit the question and add your - (NSDictionary*)elementToPropertyMappings implementation. – ugiflezet Jun 30 '11 at 08:53

1 Answers1

9

To answer your question, it looks like you do need to to both steps at the moment. Here's the code from the RKDiscussionBoardExample included with the library:

DBTopic* topic = [[DBTopic findFirstByAttribute:@"topicID" withValue:topicID] retain];
_post = [[DBPost object] retain];
_post.topicID = topic.topicID;
_post.topic = topic;

So either the relationships aren't set up properly in the example, or you really do need both steps.

Also, you should be using the newest version of RestKit which has a different object mapper and deprecates RKManagedObject. Your relationships should look something like this:

RKManagedObjectMapping* clientMapping = [RKManagedObjectMapping mappingForClass: [Client class]];
clientMapping.primaryKeyAttribute = @"clientID";
[clientMapping mapKeyPathsToAttributes:
@"id", @"clientID",
nil];

RKManagedObjectMapping* userFileMapping = [RKManagedObjectMapping mappingForClass:[UserFile class]];
userFileMapping.primaryKeyAttribute = @"userFileID";
[userFileMapping mapKeyPathsToAttributes:
 @"id", @"userFileID",
 @"client_id", @"clientID",
 nil];

[userFileMapping mapRelationship:@"client" withObjectMapping:clientMapping];
Besi
  • 22,579
  • 24
  • 131
  • 223
Evan Cordell
  • 4,108
  • 2
  • 31
  • 47