如何在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"
});
智能推荐

注意!

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



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

赞助商广告