Rails嵌套has_one:无法删除现有记录

时间:2013-01-16 03:28:29

标签: ruby-on-rails nested-attributes has-one

我正在尝试在'问题'模型中更新嵌套的question_output属性。一个问题has_one question_output。 如果数据库中没有现有的question_output,一切正常。但是如果记录已经有一个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

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', :model => "Question")
      redirect_to admin_project_question_path(@question.project, @question)
    end
  end
end

2 个答案:

答案 0 :(得分:35)

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

has_one :question_output, :dependent => :destroy

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

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

答案 1 :(得分:1)

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

= qo.hidden_field :id
相关问题