【问题标题】:POSTing complex JSON with the grape API into PostgreSQL使用葡萄 API 将复杂的 JSON 发布到 PostgreSQL
【发布时间】:2013-01-18 10:21:20
【问题描述】:

我正在尝试使用grape 创建一个 API,它会在发布时将 JSON 数据保存到 PostgreSQL。 这是示例 JSON:

{
    "about": "this is about me",
    "company_name": "David Co",
    "company_url": "http://google.com",
    "created_at": "2013-02-03T13:09:37+05:30",
    "email": "jones@david.com",
    "first_name": "David",
    "google_plus": "http://google.com",
    "id": 1
}

这是 Ruby 代码:

class Posts < Grape::API

  version 'v1', :using => :path
  format :json

  resource 'posts' do
    get "/" do
      Post.all
    end

    get "/:id" do 
      Post.find(params['id'])
    end

    post "/create" do
      Post.create(params['post'])
    end
  end

end

我正在关注这个sample,它适用于上述 JSON。

如何修改代码以使其适用于更复杂的 JSON,例如:

{
 "about": "this is about me",
 "company_name": "David Co",
 "company_url": "http://google.com",
 "created_at": "2013-02-03T13:09:37+05:30",
 "email": "jones@david.com",
 "first_name": "David",
 "google_plus": "http://google.com",
 "id": 1,
 "chall": [{
     "attributes": {
         "type": "tegory__c",
         "url": "/services0/sobjects/__c/a08Z0000000RmoTIAS"
     }
}

这是当前的数据库架构:

create_table :posts do |t|
  t.string :first_name
  t.string :email
  t.string :company_name
  t.string :google_plus
  t.string :about
  t.string :company_url
  t.timestamps
end

【问题讨论】:

  • 如果您尝试使用更复杂的 JSON,现在会发生什么? Ruby 或 PostgreSQL 中的任何错误消息?
  • 其实这行不通...我没有在 postgres 中包含这些字段。我不知道如何绘制数据库架构。我刚刚更新了当前的数据库架构

标签: ruby json postgresql grape-api


【解决方案1】:

您的attributes 将是一个单独的表,包括类型和网址。然后您的chall 将成为一个链接表,从单个posts 行映射到多个attributes 行。这使您可以将这种格式的数据放入数据库中。

当然,attributes 只有一个条目,很难提供完整的架构,但这应该让您了解如何将它们组合在一起。

请注意,如果您的 JSON 看起来像这样,您可以简化一些事情:

"chall": [{
     "type": "tegory__c",
     "url": "/services0/sobjects/__c/a08Z0000000RmoTIAS"
}]

那么chall 将是与posts 的直接一对多链接,尽管鉴于示例 JSON 中缺少数据,因此很难判断这是否有效。不过,希望这会为您指明正确的方向。

如果我假设前者,那么您的架构看起来像这样:

create_table :posts do |t|
  t.string :first_name
  t.string :email
  t.string :company_name
  t.string :google_plus
  t.string :about
  t.string :company_url
  t.timestamps
end

create_table : attributes do |t|
  t.string :type
  t.string :url
end

create_table post_attributes do |t|
  t.references : posts
  t.references : attributes
end

在这种情况下,帖子和属性之间存在多对多关系。

【讨论】:

  • 添加了表定义。
  • 好吧,我对整个葡萄 API 都是新手。我只需要对表格进行更改。不需要更改任何 ruby​​ 代码吗?
猜你喜欢
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 2015-06-13
相关资源
最近更新 更多