为什么销毁嵌套记录发生在 update_attributes 而不是父保存?

Why is destroying nested records happening on update_attributes and not on the parent save?

我有两个关联模型:

class HelpRequest < ActiveRecord::Base
  has_many :donation_items, dependent: :destroy
  accepts_nested_attributes_for :donation_items, allow_destroy: true

class DonationItem < ActiveRecord::Base
  belongs_to :help_request

我有一个验证器,如果 he/she 试图保存没有 donation_items.

help_request,则 returns 给用户一个错误
validate :has_donation_items?
...
def has_donation_items?
  if !self.donation_items.present?
    errors.add :a_help_request, "must have at least one item."
  end
end

我正在从嵌套表单中更新 help_requestdonation_items,用户可以在其中销毁单个或多个 donation_items。根据 this,如果用户销毁任何 donation_items,在保存父级之前,它们不应该在数据库中被销毁。但我已经证实,在我的情况下,它们会在 运行 update_attributes 方法后立即被销毁。这是精简代码:

@help_request.update_attributes(help_request_params) # donation items get destroyed in the database right here
# do some stuff
if @help_request.save
  #do some other stuff if the save is successful

这是具有嵌套属性的 help_request_params

def help_request_params
  params.require(:help_request).permit(:id, :name, :description, :event_flag, :due_on_event, :date, :time, :send_notification, :event_id, :invoked, donation_items_attributes: [:id, :name, :amount, :_destroy])
end

数据库似乎在 update_attributes 更新是有原因的吗?

我想我明白了。 update_attributes 立即保存(或尝试)。相反,我切换到 assign_attributes。解决了一些其他问题,但似乎已经解决了主要问题。