我正在使用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
参数传递给辅助函数。
答案 0 :(得分:1)
渲染树的标准方法是使用递归部分。要实现这一点,您首先需要向Answer
模型添加一个方法,如下所示。
def next_question
Question.find(next_question_id) if next_question_id
end
(提示:相反,您可以在belongs_to :next_question, class_name: Question
型号上设置Answer
关联
然后你创建一个像_question.json.jbuilder
这样的部分:
json.(question,:id, :text)
json.answers question.answers do |answer|
json.(answer, :id, :text)
json.partial!(:question, question: answer.next_question) if answer.next_question
end
然后在控制器中,您可以在调查中提出第一个问题并将其放入@first_question
变量中。
最后一件事:在你看来你写了
json.partial! :question, question: @first_question