ruby on rails - How to create a set of Questions and Subquestions with order? -


i have database of questions , subquestions (which belong 1 question). want subquestions ordered inside each question.

also, want bunch of main questions ordered among themselves. 1 way add order column in question , subquestion table , fill in manually. but, since db can dynamic, not viable option.

so, want is

1. root q1     a. sub1_q1     b. sub1_q2 2. root q2     a. sub2_q1     b. sub2_q2     c. sub2_q3 

i have seen gems ancestry , acts_as_tree. while possible create parent child relationship there, there no scope order bunch of siblings.

lets assume have question model has many subquestions (subquestion model). , need order questions created_at desc , subquestions created_at asc(in each question).

so models like:

class question < activerecord::base   has_many :subquestions, -> { order("created_at asc") } end class subquestion < activerecord::base   belongs_to :question end 

now do:

@questions = question.order("created_at desc").preload(:subquestions) 

this result next query:

select "questions".* "questions"  order created_at desc select "subquestions".* "subquestions" "subquestions"."question_id" in (...)  order created_at asc 

this way when you'll iterating within each question within each subquestion of question, have right order of both - question , subquestion.


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -