Rails JBuilder递归查找

时间:2015-03-17 11:40:43

标签: ruby-on-rails jbuilder

我正在使用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参数传递给辅助函数。

1 个答案:

答案 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