问题
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:
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"
});
来源:https://stackoverflow.com/questions/9299604/how-to-save-values-of-a-json-response-in-a-rails-database