2013-01-16 11 views
15

'question'모델에서 중첩 된 question_output 속성을 업데이트하려고합니다. 질문 has_one question_output. 데이터베이스에 기존 question_outputs가 없으면 모든 것이 정상적으로 작동합니다. 그러나 레코드에 이미 question_output이 있으면 업데이트를 시도 할 때 다음과 같이 표시됩니다.레일 중첩 has_one : 기존 레코드를 삭제할 수 없습니다.

기존의 관련 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 
accepts_nested_attributes

has_one :question_output, :dependent => :destroy 

:allow_destroy => true 당신이 _destroy=1 HTML의 속성을 통해 질문 양식 내에서 question_output을 삭제할 수 있습니다 : 귀하의 질문 모델에서

답변

29

은 has_one 라인을 변경합니다.

:dependent => :destroy은 질문을 삭제할 때 question_output을 삭제합니다. 또는은 question_output이 새 것으로 교체 될 때이를 삭제합니다.

+0

Ach! 물론 Devin에게 많은 감사드립니다. – PlankTon

+0

안녕하세요, 저는 이런 상황에 있습니다. 사용자가 has_one 주소를 가지고있을 때 내 사용자를 업데이트하려고하면 @PlankTon과 동일한 오류가 발생합니다. 종속성 => : destroy, 사용자를 업데이트 할 때마다 정보는 협회를 파괴하고 다른 아이디로 새로운 것을 만듭니다! 거기에 파괴없이 exeing 협회를 사용하는 방법이있다 – medBo

+2

@medBo 귀하의 질문에 대답했지만 그것이 [여기] (http://stackoverflow.com/questions/18984093/cant-update-my- 중첩 모델 - 형식 -에 - 하나 - 협회) –

1

새 레코드를 만들 때마다 오버 헤드가 발생합니다. 레코드 ID가있는 숨겨진 필드를 포함하기 만하면 삭제되는 대신 업데이트됩니다.

= qo.hidden_field :id