[英]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.