0

I want to access the Facebook Graph API and get JSON responses like this:

{
  "data": [
    {
      "name": "Coldplay", 
      "category": "Musician/band", 
      "id": "15253175252", 
      "created_time": "2012-01-27T22:51:44+0000"
    },
    {
      "name": "R.E.M.", 
      "category": "Musician/band", 
      "id": "8759772983", 
      "created_time": "2012-01-27T22:51:43+0000"
    }
  ], 
  "paging": {
    "next": "https://graph.facebook.com/1000032123447/music?format=json&limit=5000&offset=5000&__after_id=8123918"
  }
}

Now I want to save the name, the category and id into my rails database. I have got a table with the same columns.

What is the easiest way to save this response into the matching columns of the database? Or is there a better solution, i.e. just saving the whole json object into the database and read it later on in the code again?

If you have time, please provide a coding example for the javascript/jQuery (ajax maybe) and ruby code. Thank you so much!

1 Answer 1

4

See this question and answer for how to send JSON content from the browser to a Rails app.

Then you can do something like this (the JSON will be parsed automatically, and available as the params hash). One thing to note, is that the id attribute in the JSON will be ignored, since it's protected by default (Rails uses id as the primary key for records). Better to "rename it" to something like facebook_id:

# POST /path/to/collection
def create
  params["data"].each do |data|
    data["facebook_id"] = data["id"]
    SomeRecordClass.create(data)
  end
end

Of course you'll want to do some error checking, send a response, etc.

In the browser, you can do something like this, if you're using jQuery

$.ajax({
  type: "POST",
  url: "/path/to/collection",
  data: data, // the JSON data, as an object or string
  contentType: "application/json",
  dataType: "json"
});
Sign up to request clarification or add additional context in comments.

2 Comments

thanks! Could you also add the javascript to call this method, i.e. in Ajax?
@SebastianOberste-Vorth Added the bare minimum JS. The rest is up to you, though, since I'm not inclined to do all your work for you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.