У меня есть модель с именем SelectionQuestion
, которая наследуется от модели Question
, а модель Alternative
принадлежит Question
. Я использую кокон, чтобы найти форму альтернатив внутри формы selection_questions.
Моя проблема заключается в следующем:
# _form.html.haml
.modal-content
.modal-header
%button.close{"data-dismiss" => "modal", :type => "button"} ×
%h4.modal-title Selection type question
.modal-body
= simple_form_for [evaluation_template, selection_question] do |form|
= form.input :title, label: 'Question'
.alternatives
= form.simple_fields_for :alternatives do |build|
= render 'alternatives_fields', f: build
= link_to_add_association 'Add alternative', form, :alternatives, class: 'btn btn-primary', data: { association_insertion_node: '.alternatives', association_insertion_method: :append }
.modal-footer
.text-center
= button_tag class: 'btn btn-outline-success-invert' do
%i.fa.fa-plus-circle
%span
Add question
Таким образом, сервер выдает мне эту ошибку
ActionView::Template::Error (unknown attribute 'selection_question_id' for Alternative.):
И это правильно, потому что атрибут должен быть question_id
Мои модели
question.rb
class Question < ActiveRecord::Base
belongs_to :evaluation_template
end
selection_question.rb
class SelectionQuestion < Question
has_many :alternatives, dependent: :destroy
accepts_nested_attributes_for :alternatives, allow_destroy: true, reject_if: proc { |att| att['content'].blank?}
end
alternative.rb
class Alternative < ActiveRecord::Base
belongs_to :question
end
selection_questions_controller.rb
class SelectionQuestionsController < ApplicationController
before_action :set_evaluation_template
before_action :set_selection_question, only: [:edit, :update, :destroy]
def new
@selection_question = SelectionQuestion.new
end
def edit;end
def create
@selection_question = SelectionQuestion.new(selection_question_params)
@selection_question.evaluation_template = @evaluation_template
@saved = @selection_question.save
end
def update
@updated = @selection_question.update(selection_question_params)
end
def destroy
@destroyed = @selection_question.destroy
end
private
def set_evaluation_template
@evaluation_template = EvaluationTemplate.find(params[:evaluation_template_id])
end
def set_selection_question
@selection_question = SelectionQuestion.find(params[:id])
end
def selection_question_params
params.require(:selection_question).permit(:title, alternatives_attributes: Alternative.attribute_names.map(&:to_sym).push(:_destroy))
end
end