I used to have the following code to save an array of "friends" IDs (the Facebook User IDs imported via the Graph API and Omniauth) to a User model:
class User < ActiveRecord::Base
...
serialize :friends
def self.from_omniauth(auth)
require 'net/http'
require 'json'
where(auth.slice(:provider, :uid, :email, :image)).first_or_initialize.tap do |user|
user.provider = auth.provider
user.uid = auth.uid
user.oauth_token = auth.credentials.token
friendsInfo = Net::HTTP.get(URI("https://graph.facebook.com/" + auth.uid + "/friends?fields=installed&access_token=" + user.oauth_token))
unless friendsInfo == nil
friendsData = (JSON.parse(friendsInfo))["data"]
fArr = []
friendsData.each do |fD|
if fD["installed"] == true
fArr.push(fD["id"])
end
end
end
user.friends = fArr
user.save!
end
end
This code saves the User IDs of Facebook friends who also have the app installed to an array, i.e. ["3232344", "2342434", "8738453"]
.
However, I decided to change serialize :friends
to serialize :friends, JSON
for security issues, as per CodeClimate's advice, but now it either:
a) saves it all as one JSON string (if there are multiple "friends"), or
b) gives a 795: unexpected token at ''[user ID here]' - ---'
error if there is just one "friend" who also has app installed.
This answer has a comment asking how to make this work in Rails 4, so I'm guessing simply adding JSON
worked in Rails 3.1 but doesn't any more? I've tried variations of to_json
, ActiveSupport::JSON.decode
, etc., and writing a custom serializer, but my guess is my error is something to do with serializing after creating the array in my current code? Is a callback the answer?