【发布时间】:2018-08-01 00:33:15
【问题描述】:
具有以下自相关多对多设置:
class Item < ApplicationRecord
has_many :joins, dependent: :destroy
has_many :child_items, through: :joins
end
class Join < ApplicationRecord
belongs_to :item
belongs_to :child_item, class_name: 'Item'
end
重建完整树的 json 表示最直接的模式是什么?喜欢:
[
{
id: 1,
child_items: [
{
id: 2,
child_items: [
{
id: 3,
child_items: etc… untils there are no more
}
]
]
}, {
id: 4,
child_items: { etc... }
}, etc…
]
到目前为止,我有以下简单内容:
def render
iterate(entrypoint_item)
end
def iterate(node)
h = JSON.parse(node.to_json)
h['child_items'] = []
node.child_items.collect{ |child|
h['child_items'] << iterate(child)
}
h.delete('child_items') if h['child_items'].length <= 0
h
end
有没有更多的 ruby/rails 方式来完成这个?
【问题讨论】:
-
除了未确定的
JSON.parse(node.to_json),没关系 -
也许可以试试
node.as_json? -
实际上不好的是它会导致许多数据库查询,这就是像祖先这样的宝石在一个查询中获取所有树成员的地方
-
@apneadiving 同意我问的问题;也就是说,我前段时间检查过那个宝石,因为它听起来像是首选;但如果我没记错的话,你不会得到多对多的处理,对吧?从 2012 年开始,但听起来像 github.com/stefankroes/ancestry/issues/94#issuecomment-6755069 它永远不会被计划
-
虽然很多人在树上感觉很奇怪,但我能理解你会需要它
标签: ruby-on-rails arrays ruby object activerecord