congaengr / soapforce

Salesforce SOAP API wrapper based on Savon
MIT License
26 stars 25 forks source link

Ability to establish foreign key relationships using external IDs #10

Closed hamza closed 8 years ago

hamza commented 8 years ago

I wrote some code that handles this concept (described here and other random places on the web).

The basic idea is, during an upsert call, you know the Salesforce external identifier of your record(s), but what if you want to also set up relationships using the external ID of the object on the other side of the relation?

It turns out Salesforce supports this concept. Originally, in my project that makes use of this gem, I figured out how to build a hash that would eventually translate into the requisite nested XML element that the SOAP API would understand.

But I figured, that would be nifty if the client knew how to do that!

The approach is three-fold -

  1. Allow a new syntax for representing the relationship. The relationship name, followed by a dot, followed by the external ID field on the related object. In the case of custom relationships, it uses the double-underscore “r” syntax (__r). This is reminiscent of how Apex and SOQL handle related object lookups. For instance -
data = {
  "Ext_ID__c" => 1234,
  "FooField__c" => "BarValue"
  "FooRelation__r.Ext_ID__c" => 5678
}
  1. In the subjects_hash method on the Client class, perform a check for input hash keys containing this ‘dot’ syntax. If so, call the related_external_id_references routine.
  2. In the related_external_id_references routine, perform a describe call on the sObject type in question. Split the dot-syntax hash key into parts. The first part is the relationship name, which is used to look in the sObject metadata for the target object’s actual name (since the relationship name can differ from the sObject name). Then build the proper nested hash.

I’ll be using my forked version for my project, but feel free to merge this in if you would like to add this functionality to the main gem!

I also added a snippet to the Readme describing how to use.

hamza commented 8 years ago

Just saw the procedure to create a feature branch.

Closing this PR and opening a new one in a branch