繁体   English   中英

Rails:在保存之前丢弃子记录

[英]Rails: discard child record before saving

如果满足条件,我正在尝试在其父项保存在 Rails 回调中之前丢弃关联的记录。 执行throw:abort不会阻止记录保存。 难道我做错了什么?

class Document < ApplicationRecord 
  has_many :frames, as: :parent, dependent: :destroy
  has_many :frame_variables, through: :frames, dependent: :destroy

  accepts_nested_attributes_for :frames, allow_destroy: true
end

class Frame < ApplicationRecord
  belongs_to :parent, polymorphic: true
  has_many :frame_variables
end

class FrameVariable < ApplicationRecord
  belongs_to :frame
  
  attr_accessor :_delete

  before_save :discard_if_cleared

  def discard_if_cleared
    throw :abort if _delete == true
  end
end
def create
  @document = current_user.documents.new(document_params)
  if @document.save
    redirect_to documents_path
  else
    redirect_to new_document_path(template: @document.template), flash: { error: "The document you tried to create was invalid: #{@document.errors.full_messages}" }
  end
end

我错过了什么?

您在这里可能有两个选择:

  1. 要使用accepts_nested_attributes_for:reject_if块的组合,通过检查:reject_if _delete中的 _delete 有条件地不保存关联。

发现在您当前的设置中,您的accepts_nested_attributes_for位于 Document 而不是 Frame 上。 如果这可以改变,这可能会奏效。

  1. 不要使用嵌套属性一次性构建文档 object。 而是在create操作中“打开”您的参数。 基于_deleteFrameVariable构建Frame及其相关子项。 并像往常一样使用build将最终Frame “附加”到文档

抱歉,答案含糊不清,但不了解模型的完整上下文以及可以修改的内容,这些是我能想到的一般方法。

最后在before_save中执行它是一个坏主意,因为当您使用accepts_nested_attributes_for构建完整的 model 时,rails 将使用提交块并在链中的某些内容拒绝它时恢复所有内容。

该博客详细介绍了使用:reject_if

https://www.pluralsight.com/guides/ruby-on-rails-nested-attributes

这是使用拒绝块的另一个示例:

Rails:仅对嵌套属性的 CREATE 操作使用 REJECT_IF

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM