加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:08:16 所属栏目:百科 来源:网络整理
导读:我试图在“问题”模型中更新嵌套的question_output属性.一个问题has_one question_output.如果数据库中没有现有的question_outputs,一切都正常.但是如果该记录已经有一个question_output,那么在尝试更新时,我会得到以下内容: Failed to remove the existing
我试图在“问题”模型中更新嵌套的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,当它被一个新的替换.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读