ruby-on-rails – Rails嵌套has_one:不能删除现有记录

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – Rails嵌套has_one:不能删除现有记录前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在“问题”模型中更新嵌套的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

解决方法

在您的问题模型中,将has_one行更改为:
has_one :question_output,:dependent => :destroy

:allow_destroy => accept_nested_attributes上的true可以通过_destroy = 1 HTML属性从问题表单中删除一个question_output.

The:dependent => :当你删除问题时,destroy会删除question_output.或者在你的情况下删除question_output,当它被一个新的替换.

原文链接:https://www.f2er.com/ruby/272738.html

猜你在找的Ruby相关文章