Rails 6 + Cocoon双层嵌套表单渲染问题求助
Rails 6 + Cocoon原生JS版双层嵌套表单渲染问题
环境与需求
- 基于Rails 6 + Cocoon原生JS版开发测验类网站
- 需在单页完成测验、问题及对应答案的创建,采用双层嵌套表单实现
模型代码
Test模型
class Test < ApplicationRecord belongs_to :author, class_name: 'Teacher' belongs_to :article, optional: true has_many :questions, dependent: :destroy accepts_nested_attributes_for :questions, reject_if: :all_blank end
Question模型
class Question < ApplicationRecord belongs_to :test has_many :answers, dependent: :destroy accepts_nested_attributes_for :answers, reject_if: :all_blank validates :title, presence: true end
Answer模型
class Answer < ApplicationRecord belongs_to :question validates :content, presence: true validate :validate_max_answer_amount, on: :create scope :correct, -> { where(correct: true) } private def validate_max_answer_amount errors.add :base, :invalid_amount, message: 'Too many answers!' if question.answers.count >= 5 end end
问题现象
- 初始表单显示正常
- 添加答案后,新字段未显示在旧字段下方
- 添加问题后,新问题字段未在已有字段下方显示,且无默认答案输入字段
视图代码
tests/_form.html.slim
=render 'shared/errors', object: @test =form_with model: [:teacher, @test], local: true do |f| =f.number_field :author_id, class: 'hidden' =f.number_field :article_id, class: 'hidden' .mb-3.add-questions p | Add questions: .mb-3 =f.fields_for :questions do |q| =render 'teacher/questions/question_fields', f: q br br =link_to_add_association 'Add one more question', f, :questions, partial: 'teacher/questions/question_fields' =f.submit 'Submit', class: 'btn btn-outline-success btn-lg mb-4'
questions/_question_fields.html.slim
.mb-3.row .col-sm-2.col-form-label =f.label :title, 'Title' .col-sm-10.col-form-label =f.text_field :title, class: 'form-control' =f.fields_for :answers do |a| =render 'teacher/answers/answer_fields', f: a =link_to_add_association 'Add one more answer', f, :answers, partial: 'teacher/answers/answer_fields'
answers/_answer_fields.html.slim
.mb-1.row .col-sm-1 .col-sm-2.col-form-label =f.label :content, 'Enter content' .col-sm-8.col-form-label =f.text_field :content, class: 'form-control' .col-sm-1.col-form-label =f.check_box :correct, {class: 'form-check-input'}, true, false
已尝试方案及求助
移除questions/_question_fields.html.slim中的=render 'teacher/answers/answer_fields'代码后,新增问题无答案字段的问题仍未解决,也未找到答案字段显示位置异常的解决方法,恳请协助!
内容的提问来源于stack exchange,提问作者hjbaa
相关产品推荐
相关产品推荐

