簡體   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