[英]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
我错过了什么?
您在这里可能有两个选择:
accepts_nested_attributes_for
和:reject_if
块的组合,通过检查:reject_if
_delete
中的 _delete 有条件地不保存关联。 发现在您当前的设置中,您的accepts_nested_attributes_for
位于 Document 而不是 Frame 上。 如果这可以改变,这可能会奏效。
create
操作中“打开”您的参数。 基于_delete
的FrameVariable
构建Frame
及其相关子项。 并像往常一样使用build
将最终Frame
“附加”到文档抱歉,答案含糊不清,但不了解模型的完整上下文以及可以修改的内容,这些是我能想到的一般方法。
最后在before_save
中执行它是一个坏主意,因为当您使用accepts_nested_attributes_for
构建完整的 model 时,rails 将使用提交块并在链中的某些内容拒绝它时恢复所有内容。
该博客详细介绍了使用:reject_if
https://www.pluralsight.com/guides/ruby-on-rails-nested-attributes
这是使用拒绝块的另一个示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.