我使用的是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参数传递给助手函数。
发布于 2015-03-17 12:03:47
绘制树的标准方法是使用递归的部分。要实现这一点,首先需要向Answer模型添加如下方法。
def next_question
Question.find(next_question_id) if next_question_id
end(提示:您可以在Answer模型上设置一个belongs_to :next_question, class_name: Question关联。)
然后创建一个像_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_questionhttps://stackoverflow.com/questions/29098154
复制相似问题