1

每个公司都应该有一个 CompanyContact。我的公司表单包含公司联系人字段。当我更新公司并添加新的公司联系人时,它工作正常,因为在公司的显示页面中,它确实显示了新的公司联系人。但是,当我单击将我带到编辑页面的编辑链接时(注意:我什至还没有单击更新按钮),在公司联系人应该是空白的编辑公司表单中。所以我检查了日志,公司联系人被删除了。

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
4

2 回答 2

2

在您的编辑操作中,您正在为您的公司建立一个公司联系人,但您的公司只有一个公司联系人。在构建新的之前检查是否存在:

company_contact = @company.company_contact || @company.build_company_contact
于 2012-03-08T21:33:17.093 回答
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操作不应建立关联记录。

于 2012-03-08T21:29:31.847 回答