У меня есть опрос как часть приложения, которое я создаю. Пользователь может создавать опрос и задавать вопросы динамически (может иметь столько, сколько он хочет), поэтому я использовал связанную модель с:
#survey.rb
has_many :survey_questions, :dependent => :destroy
has_many :survey_answers, :dependent => :destroy
after_update :save_survey_questions
validates_associated :survey_questions
def save_survey_questions
survey_questions.each do |t|
if t.should_destroy?
t.destroy
else
t.save(false)
end
end
end
def survey_question_attributes=(survey_question_attributes)
survey_question_attributes.each do |attributes|
if attributes[:id].blank?
survey_questions.build(attributes)
else
survey_question = survey_questions.detect { |e| e.id == attributes[:id].to_i }
survey_question.attributes = attributes
end
end
end
#surveys_controller.rb
def new
@survey = Survey.new
if(@survey.survey_questions.empty?)
@survey.survey_questions.build
end
respond_to do |format|
format.html # new.html.erb
end
end
def create
@survey = Survey.new(params[:survey])
respond_to do |format|
if @survey.save
format.html { redirect_to(survey_path(:id => @survey)) }
else
format.html { render :action => "new" }
end
end
end
#survey_question.rb
class SurveyQuestion < ActiveRecord::Base
belongs_to :survey
attr_accessor :should_destroy
def should_destroy?
should_destroy.to_i == 1
end
validates_presence_of :question, :survey_id
end
Проблема в том, что при отправке я получаю сообщение об ошибке:
@ errors = {"survey_questions" => ["Недопустимо", "Недопустимо", "Недействительно"]}
Я полагаю, что это потому, что survey_id, с которым я связываю опросы и survey_questions, не заполняется.
Есть идеи, как мне это преодолеть?
Если я создаю опрос без вопросов, а затем добавляю их через редактирование, тогда он отлично работает.