23

我正在尝试更新“问题”模型中的嵌套 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
4

2 回答 2

47

在您的问题模型中,将 has_one 行更改为:

has_one :question_output, :dependent => :destroy

上允许您通过HTML 属性从问题表单:allow_destroy => true中删除 question_output。accepts_nested_attributes_destroy=1

:dependent => :destroy删除问题时会删除 question_output 。或者在您的情况下,将 question_output 替换为新问题时会删除它。

于 2013-01-16T04:10:06.480 回答
0

每次创建新记录都是某种开销。您只需包含带有记录 id 的隐藏字段,它将被更新而不是销毁

= qo.hidden_field :id
于 2014-07-16T22:44:13.930 回答