我正在尝试将论坛中的数据写入JSON文件。 JSON文件中的层次结构应该看起来像这样:
thread_id
post_id
...some_items...
或更具体地说:
{
"0101": {
"title": "Hi everybody",
"1001": {...},
"1002": {...}
},
}
我的函数中的相关部分如下所示:
return {
thread_id.to_i => {
:title => title,
post_id.to_i => {...}
}
}
结果是每个帖子都成为新父thread_id
的孩子:
{
"0101":{
"title":"Hi everybody",
"1001":{...}
},
"0101":{
"1002":{...}
}
}
我做错了什么?
答案 0 :(得分:1)
首先,在我看来,你试图实现的JSON模式并不完全正确。看看你怎么看:
{
"threads": [
{
"id": 100,
"title": "Lorem ipsum dolor sit amet",
...
"posts": [
{
"id": 1000,
"body": "Lorem ipsum dolor sit amet",
...
},
...
]
},
...
]
}
你的问题的答案取决于你的数据是如何开始的,我们不知道,所以我将回答我对数据结构的期望。 (注意:不要使用常量Thread
;它已经是一个用于完全不相关的Ruby类。)
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": [...] }