2

投稿時にJSONデータをPostgreSQLに保存するgrapeを使用してAPIを作成しようとしています。サンプル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

私はこのサンプルに従っています。これは上記の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
4

1 に答える 1

1

タイプattributesとURLを含む別のテーブルになります。次にchall、単一のposts行から複数​​のattributes行にマップするリンク テーブルになります。これにより、この形式のデータをデータベースに入れることができます。

もちろん、エントリが 1 つしかないattributesため、完全なスキーマを提供することは困難ですが、これにより、それらをまとめる方法についてのアイデアが得られるはずです。

必要に応じて、JSON が次のように単純化できることに注意してください。

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

これはchallへの直接的な 1 対多のリンクになり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

この場合、投稿と属性の間に多対多の関係があります。

于 2013-02-03T16:35:10.173 に答える