我正在尝试更新“问题”模型中的嵌套 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 会解决这个问题,但是唉 - 没有乐趣。诚然,我以前没怎么用过 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
问题 Controller :
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
最佳答案
在您的问题模型中将 has_one 行更改为:
has_one :question_output, :dependent => :destroy
accepts_nested_attributes
上的 :allow_destroy => true
允许您通过 _destroy=1
HTML 从问题表单中删除 Question_output属性。
当您删除问题时,:dependent => :destroy
会删除 Question_output。 或者在您的情况下在 Question_output 被新输出替换时将其删除。
关于ruby-on-rails - Rails 嵌套 has_one : cannot delete existing record,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14350914/