【问题标题】:Rails nested has_one: cannot delete existing recordRails嵌套has_one:无法删除现有记录
【发布时间】:2013-01-16 03:28:28
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

    has_one :question_output, :dependent => :destroy
    

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

    :dependent =&gt; :destroy 会在您删除问题时删除 question_output。 或者在您的情况下在 question_output 被新的替换时删除它。

    【讨论】:

    • 嗨,我处于这种情况,当我尝试更新我的用户时,我有一个用户 has_one 地址,如果我使用 :dependent =>,它会给我与@PlankTon 相同的错误:销毁,每次我更新用户信息时,它都会破坏关联并创建一个具有不同 ID 的新关联!有一种方法可以在不破坏的情况下使用现有的关联然后创建它
    • @medBo 正要回答你的问题,但看到它得到了回答here
    【解决方案2】:

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

    = qo.hidden_field :id
    

    【讨论】:

    • 您不认为这是一个巨大的安全风险吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多