2013-02-03 5 views
2

게시 할 때 JSON 데이터를 PostgreSQL에 저장하는 grape을 사용하여 API를 만들려고합니다. 나는 위의 JSON과 잘 작동이 sample, 다음있어포도 API가있는 복잡한 JSON을 PostgreSQL에 게시

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 

:

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

이 루비 코드는 다음과 같습니다 다음은 샘플 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": "[email protected]", 
"first_name": "David", 
"google_plus": "http://google.com", 
"id": 1, 
"chall": [{ 
    "attributes": { 
     "type": "tegory__c", 
     "url": "/services0/sobjects/__c/a08Z0000000RmoTIAS" 
    } 
} 

가 본 데이터베이스 스키마입니다 : : 나는 같은 더 복잡한 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 
+0

좀 더 복잡한 JSON을 사용하려고하면 어떻게됩니까? Ruby 또는 PostgreSQL의 모든 오류 메시지? – jgm

+0

실제로 실제로 그 실 거예요 ... 내가 havent postgres.I 그 필드를 포함하는 데이터베이스 스키마를 그리는 방법을 모르겠다. 난 그냥 현재 데이터베이스 스키마를 업데이 트 – iJade

답변

1

당신의 attributes는 별도의를 될 것입니다 테이블 (유형 및 URL 포함). 그러면 chall은 단일 posts 행에서 복수 attributes 행까지 매핑하는 링크 테이블이 될 것입니다. 따라서이 형식의 데이터를 데이터베이스에 저장할 수 있습니다.

물론 attributes에 대한 항목이 하나 뿐인데 완벽한 스키마를 제공하기는 어렵지만이 방법을 함께 사용하는 방법에 대한 아이디어를 얻을 수 있습니다. 당신이 원하는 경우 JSON이 닮은 경우에 당신이 일을 단순화 할 수

참고 :

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

다시이 경우 말하기 어렵다하더라도 그런 다음 challposts에 직접 일대 다 연결이 될 것입니다 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 

: 나는 전자를 가정하면

는 다음 스키마는 다음과 같이 보인다.

+0

하지만 그게 필요한 루비 코드 변경 될 것이라고 – iJade

+0

테이블을 추가했습니다 정의. – jgm

+0

글쎄,이 포도 API를 처음 접했을 뿐이에요. 테이블로 chnages 만 만들어야 만합니다. 루비 코드를 바꿀 필요가 없나요? – iJade