我正在尝试更新“问题”模型中的嵌套 question_output 属性。一个问题 has_one question_output。如果数据库中没有现有的 question_outputs,则一切正常。但是,如果记录已经有 question_output,我在尝试更新时会得到以下信息:
无法删除现有的关联 question_output。将外键设置为 nil 后,记录无法保存。
我原以为 allow_destroy 会解决这个问题,但可惜 - 不高兴。诚然,我以前没有使用过 has_one 。但是,如果有人对如何解决此问题有任何想法,我将不胜感激。相关代码如下:
表格:
= form_for [@question.project, @question], :as => :question, :url => admin_project_question_path(@question.project, @question) do |f|
= render '/shared/form_errors', :model => @question
= f.fields_for :question_output_attributes do |qo|
.field
= qo.label :question_type
= qo.select :question_type, QuestionOutput::QUESTION_TYPES
.field
= qo.label :client_format
= qo.select :client_format, QuestionOutput::CLIENT_FORMATS
.field
= qo.label :required
= qo.check_box :required
.field
= qo.label :min_input, 'Length'
= qo.text_field :min_length
= qo.text_field :max_length
= f.submit 'Save Question Formatting'
问题模型:
class Question < ActiveRecord::Base
has_one :question_output
accepts_nested_attributes_for :question_output, :allow_destroy => true
end
问题输出模型:
class QuestionOutput < ActiveRecord::Base
belongs_to :question
end
问题控制器:
class Admin::QuestionsController < ApplicationController
def show
@question = Question.find(params[:id])
@question.question_output ||= @question.build_question_output
end
def update
@question = Question.find(params[:id])
if @question.update_attributes(params[:question])
flash[:notice] = t('models.update.success', :model => "Question")
redirect_to admin_project_question_path(@question.project, @question)
else
flash[:alert] = t('models.update.failure', :model => "Question")
redirect_to admin_project_question_path(@question.project, @question)
end
end
end