Rails将has_one关系的外键更新为nil

时间:2018-01-12 19:21:24

标签: ruby-on-rails associations belongs-to has-one

我有一个与附件模型具有has_one关系的Anexo模型

class Anexo < ApplicationRecord
  validates :descricao, presence: true, uniqueness: true
  has_one :attachment,  dependent: :restrict_with_error, validate: true
end

class Attachment < ApplicationRecord
  validates :nome, :tamanho, :anexo, presence: true
  belongs_to :anexo 
end

在我的AnexosController中,

def update
   @anexo.build_attachment(attachment_params)
   respond_to do |format|
     if @anexo.update(anexo_params)
        format.html { redirect_to @anexo, notice: 'Anexo was successfully updated.' }
        format.json { render :show, status: :ok, location: @anexo }
     else
       format.html { render :edit }
       format.json { render json: @anexo.errors, status: :unprocessable_entity }
    end
  end
end

当我创建新记录时,everythig工作正常,当我将atachment留空时会显示正确的错误消息。

当我编辑此注册表并且不选择任何附件时,它会显示该消息,但外键设置为nil。

如果我取消操作并返回,则记录已更新且anexo不再具有旧附件。

您是否想知道是否可以阻止在build_attachment中发生此更新?

0 个答案:

没有答案
相关问题