Ruby / Rails: how can I create multiple records in

2020-07-18 06:48发布

问题:

I'm using the rforce gem to create records in my salesforce database.

The example for creating records in the rforce documentation is:

  opportunity = [
                 :type,      'Opportunity',
                 :accountId, account_id,
                 :amount,    '10.00',
                 :name,      'Fakey McFakerson',
                 :closeDate, '2008-07-04',
                 :stageName, 'Closed Won'
                ]

  binding.create :sObject => opportunity

The salesforce API call create() allows for the creation of multiple object at once, but I'm struggling to accomplish this. I've tried the following call:

binding.create :sObject => array_of_opportunities

Where array_of_opportunities is an array of arrays like opportunity in the example above.

but that throws an error:

NoMethodError (undefined method `to_sym' for #<Array:0x00000004ba5488>)

I'd appreciate any help.

回答1:

To bulkify the API operations, wrap the request in another array with some consistent symbol (i.e. :sObjects) as the key for each value. The same symbol should be repeated before each value, as this gets converted into the repeated XML child elements. For example, if you want to create two opportunities, do this:

opportunity1 = [
    :type,      'Opportunity',
    :amount,    '10.00',
    :name,      'OPP1',
    :closeDate, '2008-07-04',
    :stageName, 'Closed Won'
]

opportunity2 = [
    :type,      'Opportunity',
    :amount,    '10.00',
    :name,      'OPP2',
    :closeDate, '2008-07-04',
    :stageName, 'Closed Won'
]

puts binding.create([:sObjects, opportunity1, :sObjects, opportunity2])

This XML is created behind the scenes and sent to SFDC:

<create xmlns="urn:partner.soap.sforce.com">
  <sObjects>
    <type>Opportunity</type>
    <amount>10.00</amount>
    <name>OPP1</name>
    <closeDate>2008-07-04</closeDate>
    <stageName>Closed Won</stageName>
  </sObjects>
  <sObjects>
    <type>Opportunity</type>
    <amount>10.00</amount>
    <name>OPP2</name>
    <closeDate>2008-07-04</closeDate>
    <stageName>Closed Won</stageName>
  </sObjects>
</create>

and here is the response for the two opportunities being created at once:

{:createResponse=>{:result=>[{:id=>"0066000000KNMrOAAX", :success=>"true"}, {:id=>"0066000000KNMrPAAX", :success=>"true"}]}}

Note, you can create up to 200 records at a time.

Also, I noticed that if the two values are the same exact object (i.e. doing something like binding.create([:sObjects, opportunity1, :sObjects, opportunity1]), the XML converter freaks out, so make sure they are actually separate objects. This is probably a bug in the framework, but it is such a rare case in actual production situations to be considered serious, but watch out for it while you are testing.