Rails JBuilder 递归查找
Rails JBuilder recursive lookup
我用的是Rails4,有一些简单的模型如下:
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
参数传递给辅助函数。
渲染树的标准方法是使用递归部分。要实现这一点,您首先需要像这样向 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_question
我用的是Rails4,有一些简单的模型如下:
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
参数传递给辅助函数。
渲染树的标准方法是使用递归部分。要实现这一点,您首先需要像这样向 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_question