2012-03-08 7 views
1

모든 회사는 하나의 CompanyContact가 있어야합니다. 회사 양식에는 회사 연락처 필드가 있습니다. 회사를 업데이트하고 새로운 회사 연락처를 추가하면 회사의 표시 페이지에서 새 회사 연락처가 표시되므로 제대로 작동합니다. 그러나 편집 링크 (아직 편집 단추를 클릭하지 않은 상태)로 이동하는 편집 링크를 클릭하면 회사 연락처가 비어 있어야하는 편집 회사 양식이 비어 있습니다. 그래서 로그를 확인하고 companycontact가 삭제되었습니다. 내가 어떤 삭제 작업 호출되지 않았기 때문에Rails 3. 편집 페이지로 이동하면 중첩 된 레코드가 삭제되는 이유는 무엇입니까?

DELETE FROM "company_contacts" WHERE "company_contacts"."id" = ? [["id", 4]]

나는 혼란 스러워요.

---------------------------------------- 
company.rb 
has_one :company_contact, :dependent => :destroy 
accepts_nested_attributes_for :company_contact 

---------------------------------------- 
company_contact.rb 
belongs_to :company 

---------------------------------------- 
companies_controller.rb 
def new 
    @company = Company.new 
    company_contact = @company.build_company_contact 
    respond_to do |format| 
    format.html # new.html.erb 
    format.json { render json: @company } 
    end 
end 

def edit 
    @company = Company.find(params[:id]) 
    company_contact = @company.build_company_contact 
end 
+2

'has_one' 관계에 대해'@ company.build_company_contact'가 연관된 레코드를 삭제한다고 생각합니다. 나는 이것이 정당하다는 것을 알 수 있지만, 약간의 의외입니다. –

+0

제공된 코드로 db에 레코드가 저장되지 않으므로 삭제가 정당화 될 수있는 방법을 알 수 없습니다. – UncleGene

+0

@UncleGene 게시 한 코드가 전체 내용을 전제로한다고 가정하는 것은 잘못된 것입니다. 그는 창조 활동에 의해 구원받지 못한 기록에 관해서는 아무 말도하지 않았습니다. 따라서 필자는 예상대로 레코드의 편집 작업을 수행한다는 가정하에 작업하고 있습니다. –

답변

1

내가 위에 댓글 의혹을 확인하는 액티브 소스,이 발견 (코드에 주석 아래 나의 것이) :

class HasOneAssociation < SingularAssociation #:nodoc: 
    def replace(record, save = true) 
    raise_on_type_mismatch(record) if record 
    load_target 

    reflection.klass.transaction do 
     # !!! 
     # This is where your record is getting deleted 
     # !!! 
     if target && target != record 
     remove_target!(options[:dependent]) unless target.destroyed? 
     end 

     if record 
     set_owner_attributes(record) 
     set_inverse_instance(record) 

     if owner.persisted? && save && !record.save 
      nullify_owner_attributes(record) 
      set_owner_attributes(target) if target 
      raise RecordNotSaved, "Failed to save the new associated #{reflection.name}." 
     end 
     end 
    end 

    self.target = record 
    end 
... 

replace 방법은 record.build_association가있을 때마다 호출 할 나타납니다 익숙한.

귀하의 edit 작업은 이미 존재하는 경우 연결된 레코드를 작성하지 않아야합니다.

2

편집 작업에서 회사 연락처를 만들고 있지만 회사 연락처는 하나뿐입니다.

company_contact = @company.company_contact || @company.build_company_contact