0

私のモデル:

class Topic < ActiveRecord::Base
  has_many :questions
end

class Question < ActiveRecord::Base
  belongs_to :topic
  has_many :answers, dependent: :destroy

  accepts_nested_attributes_for :answers, reject_if: :all_blank, allow_destroy: true
end

class Answer < ActiveRecord::Base
  belongs_to :question
end

私のコントローラーquestions_controller

class QuestionsController < ApplicationController
  expose(:topic) { Topic.find(params[:topic_id]) }
  expose(:question, attributes: :question_params)
  expose(:questions) { topic.questions }

  def create
    if topic.questions.create(question_params)
      redirect_to topic
    else
      render 'new'
    end
  end

  private
  def question_params
    params.require(:question).permit(
      :title,
      :instructions,
      answers_attributes: [:id, :answer, :correct, :question_id, :_destroy]
    )
  end
end

/questions/_form:

= simple_form_for [:topic, question] do |f|
  = f.input :title, label: "Question:", placeholder: "Your question here."
  = f.input :instructions, label: "Instructions:", placeholder: "If this question requires special instructions, put them here."
  %br
  %h3
    Answers
  #answers
    = f.simple_fields_for :answers do |answer|
      = render 'answer_fields', f: answer
    .links
      = link_to_add_association 'add answer', f, :answers
  = f.submit class: "button small radius expand success"

/questions/answer_fields:

.nested_fields
  = f.input :answer
  = f.input :correct, as: :boolean
  = link_to_remove_association "remove task", f

routes.rb:

Rails.application.routes.draw do
  resources :topics do
    resources :questions
  end
  root to: 'topics#index'
end

ネストされたフォームを管理するためにを使用しています。

/topics/.:id「新しい質問を追加」ボタンを押すと、パス/topics/.:id/questions/newに移動し、「回答を追加」ボタンを押すと、cocoon は回答用に 3 つの新しいスペースをレンダリングします。また、「回答の削除」リンクを押しても項目が削除されません。

ビューが 3 つの回答フィールドをレンダリングするのはなぜですか? 「回答を削除」リンクが機能しないのはなぜですか?

4

0 に答える 0