2012-03-08 9 views
1

すべての会社は1つの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

'@ company.build_company_contact'は、関連するレコードが' has_one'関係のために存在する場合、そのレコードを削除すると思います。私はこれが正当なものだと思うが、予期せぬことがある。 –

+0

レコードは提供されたコードでdbに保存されていないので、削除が正当化される方法はわかりません。 – UncleGene

+0

@UncleGene彼が投稿したコードが全話を伝えると仮定するのは間違いだと思います。彼は、作成アクションによって救われなかったレコードについて何も言わなかった。したがって、私は彼が期待するべきであるように見えるレコードのために彼が編集アクションを打っているという前提で操作しています。 –

答えて

1

私は上記にコメント疑いを確認ActiveRecordのソースにこれを見つけた(コード内のコメントは、以下の鉱山である):

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

編集アクションでは、あなたの会社の会社の連絡先を作成していますが、あなたの会社は1つの会社の連絡先しか持っていません。

company_contact = @company.company_contact || @company.build_company_contact 
関連する問題