Search code examples
ruby-on-railsrubysalesforceattachmentdatabasedotcom-gem

Salesforce REST API: Databasedotcom gem to upload attachments


I'm using Heroku's Databasedotcom gem to interact with Salesforce's REST API in my Ruby on Rails app. I can successfully create Accounts via the API, but I'm having trouble adding attachments. I've found this suggestion https://github.com/heroku/databasedotcom/issues/98 and did the following:

# Upload to Salesforce attachment
salesforce_attachment = Salesforce.client.materialize("Attachment").new
salesforce_attachment.Body = Base64::encode64(File.read(temp_file_path)) # critical line
salesforce_attachment.OwnerId = Salesforce::Sobjects::OWNER_IDS[:OWNER_ID]
salesforce_attachment.ParentId = Salesforce.find_or_create_account_for_user(user)
salesforce_attachment.Name = file_name
salesforce_attachment.IsPrivate = false
salesforce_attachment.save # this isn't saving for some reason

When I try to save, however, I get the following error:

Databasedotcom::SalesForceError: Cannot deserialize instance of reference from START_OBJECT value { at [line:1, column:2]
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/databasedotcom-1.3.2/lib/databasedotcom/client.rb:376:in `ensure_expected_response'
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/databasedotcom-1.3.2/lib/databasedotcom/client.rb:334:in `with_encoded_path_and_checked_response'
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/databasedotcom-1.3.2/lib/databasedotcom/client.rb:307:in `http_post'
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/databasedotcom-1.3.2/lib/databasedotcom/client.rb:234:in `create'
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/databasedotcom-1.3.2/lib/databasedotcom/sobject/sobject.rb:115:in `save'
from (irb):100
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/railties-3.2.17/lib/rails/commands/console.rb:47:in `start'
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/railties-3.2.17/lib/rails/commands/console.rb:8:in `start'
from /Users/oregontrail256/.rvm/gems/ruby-1.9.3-p545/gems/railties-3.2.17/lib/rails/commands.rb:41:in `<top (required)>'
from script/rails:6:in `require'
from script/rails:6:in `<main>'

I've tried different files and still get the issue. I strongly suspect this is related to setting the "Body" attribute of the attachment, but I can't figure out what I'm doing wrong because all the resources, including Salesforces' developer docs, say to base64 encode the file. Moreover I am not exceeding their 5 Mb limit. Any suggestions???


Solution

  • Ok I figured it out: when I was setting the attachment's ParentId, I was using the actual Account object, not the ID of the Account object. Ie:

    # wrong
    salesforce_attachment.ParentId = Salesforce.find_or_create_account_for_user(user)
    
    # right
    salesforce_attachment.ParentId = Salesforce.find_or_create_account_for_user(user).Id