我的模型:
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
我正在使用cocoon来管理我的嵌套表单。
当我去/topics/.:id
并按下“添加新问题”按钮时,它会将我带到/topics/.:id/questions/new
路径,当我按下“添加答案”按钮时,茧会呈现 3 个新的答案空间。此外,如果我按“删除答案”链接,这些项目不会被删除。
为什么视图呈现 3 个答案字段?为什么“删除答案”链接不起作用?