我有类似
的东西strands = Strand.all
data = {}
data["data"] = {
strands.each do |strand|
"#{strand.name}" = {"description" => "#{strand.description}",
if strand.standards.present?
"children" =>
strand.standards.each do |standard|
{"#{standard.name}" => {"description" => "#{standard.description}"}
}
end
end
}
end
}
所以我需要生成一个像下面那样的json结构
"data": {
"testStrand3Code": {
"description" : " some descr.. .",
"children" : {"standard3Code" : {
"description" : " some descr.. ."
}}
}
}
我无法迭代strands.each do |strand|
并且它给我一个错误。我想我不能在哈希{}中运行逻辑代码?我该怎么做?谢谢。
答案 0 :(得分:2)
(data = {})["data"] =
strands.map do |strand|
[strand.name,
{
"description" => strand.description,
"children" => strand.standards.map do |standard|
[standard.name, {"description" => standard.description}]
end.to_h
}
]
end.to_h