2013-01-16 27 views
15

我試圖在'問題'模型中更新嵌套的question_output屬性。問題has_one question_output。 如果數據庫中沒有現有的question_output,則一切正常。但是如果記錄已經有了一個question_output,我會在嘗試更新時得到以下結果:Rails嵌套has_one:不能刪除現有記錄

無法刪除現有的關聯question_output。外鍵被設置爲零後,記錄 未能保存。

我原以爲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 

回答

29

在你的問題的模型改變HAS_ONE行:

has_one :question_output, :dependent => :destroy 

:allow_destroy => trueaccepts_nested_attributes允許你從問題表格內通過_destroy=1 HTML屬性刪除question_output。

:dependent => :destroy在刪除問題時刪除question_output。 或者在你的情況下,刪除question_output,當它被替換爲新的。

+0

Ach!當然 - 非常感謝德文。 – PlankTon

+0

嗨,我在這樣的情況下,我有一個用戶has_one地址,當我嘗試更新我的用戶它給我與@PlankTon相同的錯誤,如果我使用:dependent =>:destroy,每次我更新用戶信息它摧毀協會,並創建一個不同的ID新的!有一種方法來使用exesting關聯而不破壞然後創建它 – medBo

+2

@medBo即將回答你的問題,但看到它得到了答案[這裏](http://stackoverflow.com/questions/18984093/cant-update-my-嵌套模型形式爲有一個關聯) –

1

每次創建新記錄都是某種開銷。 你只需要包含隱藏字段與記錄ID,它將被更新而不是銷燬

= qo.hidden_field :id