2014-10-11 5 views
-1

포럼의 데이터를 JSON 파일에 쓰려고합니다. 더 구체적으로Ruby에서 중첩 된 해시 만들기

thread_id 
    post_id 
     ...some_items... 

또는 :

{ 
    "0101": { 
     "title": "Hi everybody", 
     "1001": {...}, 
     "1002": {...} 
    }, 
} 

내 함수의 관련 부분은 다음과 같습니다

return { 
    thread_id.to_i => { 
    :title => title, 
    post_id.to_i => {...} 
    } 
} 

결과 JSON 파일의 계층 구조는 무엇인가이보고되어있다 각 게시물은 새로운 부모의 자녀가됩니다. thread_id :

{ 
    "0101":{ 
     "title":"Hi everybody", 
     "1001":{...} 
    }, 
    "0101":{ 
     "1002":{...} 
    } 
} 

내가 뭘 잘못하고 있니?

+4

당신이 당신의 방법을 더 많이 제공시겠습니까? 분명히 스레드 노드의 각 게시물을 래핑하지만 데이터를 반복하는 방법을 알아야합니다. – BroiSatse

+0

': title => title' 또는''title ":"안녕하세요 여러분 "은 내가 주장하는 JSON 형식의 어느 곳에도 맞지 않습니다. – sawa

답변

1

우선 JSON 스키마는 내 의견으로는 옳지 않습니다. 당신이 어떻게 생각하는지 참조 :

{ 
    "threads": [ 
    { 
     "id": 100, 
     "title": "Lorem ipsum dolor sit amet", 
     ... 
     "posts": [ 
     { 
      "id": 1000, 
      "body": "Lorem ipsum dolor sit amet", 
      ... 
     }, 
     ... 
     ] 
    }, 
    ... 
    ] 
} 

그리고 당신의 질문에 대한 대답은 데이터가 우리가 모르는 어떤 밖으로 시작하는 방법에 따라 달라집니다, 그래서 내가 데이터를 예상 어떤 측면에서 답변 해 드리겠습니다 모양이 보이는 구조. (참고 : 사용하지 않는 일정한 Thread, 그것은 이미 완전히 관련이없는 무언가에 사용되는 루비 클래스입니다.)

class ForumThread 

    def self.serialize(threads) 
    { threads: threads.map(&:serialize) } 
    end 

    def serialize 
    attrs_to_serialize.inject({}) do |hash, attr| 
     hash[attr] = send(attr) 
     hash 
    end 
    end 

    def serialized_posts 
    posts.map &:serialize 
    end 

    def attrs_to_serialize 
    [:id, :title, ..., :serialized_posts] 
    end 

end 

class ForumPost 

    def serialize 
    attrs_to_serialize.inject({}) do |hash, attr| 
     hash[attr] = send(attr) 
     hash 
    end 
    end 

    def attrs_to_serialize 
    # same sort of thing as above 
    # ... 
    end 

end 

# Given the `threads` variable below holds an array or array-like 
# object of ForumThread instances you could do this: 

JSON.generate ForumThread.serialize(threads) # => { "threads": [...] }