Sunday, 15 January 2012

Rails JBuilder recursive lookup -


I am using Rail 4, and I have some common models, as follows:

  class questions & lt; ActiveRecord :: Base # column (id, text) has_many: answer finished class answer & lt; ActiveRecord :: Base # column (id, text, next_translation_id) is_to: end of question  

You can see that the answer is a next_question_id column, which used to see the second question Will go I want to generate a tree-structure Jason like this:

  {"text": "this question is 1", "answer": [{"text": "This is an answer {"Text": "This question is 2", "answer": [{"text": "this answer is cited", "next_question":}]}}, {"lesson": " This answer is "," next_question ": {" text ":" this question is 2 "," answer ": [{" text ":" this is the answer "," next_question ":}}}}}}  

How can I get it with the jebolder? I tried to solve, but I can not argue json in the Helper function.

Standard rendering for rendering trees is using a recursive partial. To implement this, you will first need to add a method like your answer model.

  def next_question next.find (next_question_id) if next_question_id end  

( hint ): Alternatively, answer on the model can set a related_to: next_sion, class_name: question association)

Then you create a partially created _question. Json.jbuilder which is like this:

  json. (Question,: id, text:) JSN Objective Question. Torsors | Answers | Json Answer: (id, text) Jason Patial! Answer: answer.next_question end  

Then in the controller you first question in your survey and tell it in the @first_question variable.

And the last thing: in your thoughts you write

  json.partial! : Question, question: @first_question  

No comments:

Post a Comment