如何在rails數據庫中保存JSON響應的值?

[英]How to save values of a JSON response in a rails database?


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

我想訪問Facebook Graph API並獲取如下的JSON響應:

{
  "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.

現在我想將名稱,類別和id保存到我的rails數據庫中。我有一張相同列的表。

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?

將此響應保存到數據庫的匹配列中的最簡單方法是什么?或者是否有更好的解決方案,即只是將整個json對象保存到數據庫中並稍后再次在代碼中讀取它?

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

如果你有時間,請提供javascript / jQuery(可能是ajax)和ruby代碼的編碼示例。非常感謝!

1 个解决方案

#1


3  

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

有關如何將JSON內容從瀏覽器發送到Rails應用程序,請參閱此問題和答案。

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:

然后你可以做這樣的事情(JSON將自動解析,並作為params哈希值提供)。需要注意的一點是,JSON中的id屬性將被忽略,因為它默認受保護(Rails使用id作為記錄的主鍵)。最好將其“重命名”為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

在瀏覽器中,如果您使用的是jQuery,則可以執行此類操作

$.ajax({
  type: "POST",
  url: "/path/to/collection",
  data: data, // the JSON data, as an object or string
  contentType: "application/json",
  dataType: "json"
});

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2012/02/15/720233ef0f65a7607a41d3ab3b13a55b.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com