我试图在“问题”模型中更新嵌套的question_output属性.一个问题has_one question_output.如果数据库中没有现有的question_outputs,一切都正常.但是如果该记录已经有一个question_output,那么在尝试更新时,我会得到以下内容:
Failed to remove the existing associated question_output. The record
Failed to save when after its foreign key was set to nil.
我会以为allow_destroy会照顾,但唉 – 没有快乐.诚然,我以前没有使用过.但是如果有任何关于如何解决这个问题的想法,我会感激的.相关代码如下:
表格:
= 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
QuestionOutput模型:
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',@question) end end end