【发布时间】:2015-03-17 11:40:42
【问题描述】:
我使用的是 Rails 4,我有一些简单的模型如下:
class Question < ActiveRecord::Base
# columns (id, text)
has_many :answers
end
class Answer < ActiveRecord::Base
# columns (id, text, next_question_id)
belongs_to :question
end
您可以看到一个答案有一个 next_question_id 列,该列将用于查找另一个问题。我想生成一个像这样的树结构 json:
{
"text": "This is question 1",
"answers": [
{
"text": "This is answer a",
"next_question": {
"text": "This is question 2",
"answers": [
{
"text": "This is answer c",
"next_question":
}
]
}
},
{
"text": "This is answer b",
"next_question": {
"text": "This is question 2",
"answers": [
{
"text": "This is answer d",
"next_question":
}
]
}
}
]
}
如何使用 JBuilder 实现这一点?我尝试了here 的解决方案,但我无法将json 参数传递给辅助函数。
【问题讨论】: