私は、階層実装にgem Ancestryを使用しているRails4.0アプリケーションに取り組んでいます。多くの質問があるテンプレート モデルがあります。これらの質問モデルをグループ化およびサブグループ化できなければなりません。各テンプレートには多くの質問グループを含めることができ、これらの質問グループの下に、多くの質問または質問のサブグループのいずれかを含めることができます (ただし、両方を含めることはできません)。ちなみに関係するモデルは「テンプレート」と「クエスチョン」の2つだけです。例えば:
Template
QuestionGroup1
Question_Subgroup1
Question 1
Question 2
QuestionGroup2
Question_Subgroup1
Question_Subgroup2
QuestionGroup3
Question1
Question2
Question3
例が混乱しないことを願っています。Ancestry を使用して、親の下に子を作成することはできますが、グループ化を行うことはできません。この点で私を導いてください。
以下のコードを投稿しています。
テンプレート モデル
class Template < ActiveRecord::Base
has_many :questions
accepts_nested_attributes_for :questions, allow_destroy: true, reject_if: proc { |attributes| attributes.all? { |key, value| key == '_destroy' || value.blank? } }
end
質問モデル
class Question < ActiveRecord::Base
has_ancestry
belongs_to :template
end
Question Index.html.haml ページのコードは次のとおりです。
%h4 Template Details
%hr
.row-fluid
.span4
%fieldset.template_outline
%strong Template Outline
%br
= link_to 'Add Group', new_template_path(@template), id: "add_question_group"
%hr
= render 'questions_group'
%br/
Question_group 部分的
%ul.questions_group
- @questions.roots.each do |question|
%ul#questions_sub_group
- question.subtree.each do |questions_sub_group|
%li= link_to questions_sub_group.text_brief, edit_template_question_path(questions_sub_group.template, questions_sub_group)
= link_to 'Add Question', new_template_requirement_path(@template, parent_id: requirement)
= link_to 'Delete Question', [question.template, question], :method => :delete, :data => { :confirm => 'Are you sure?' }
ご覧のとおり、1 つの質問を追加および削除できます。それらをグループ化できるようにしたい。他のモデルを使わなくてもできますか?質問グループと単一の質問の違いは、グループには「タイトル」しかないのに対し、質問には「タイトル」と「説明」があることです。