當我創建一個Blog物件時,回呼create和update回呼都是按順序觸發的。
在這種情況下,更新Blog物件會洗掉所有現有物件images并生成新物件。我只想在 上生成新images的create,然后在 上洗掉并重新創建它們update。
我認為這是由于嵌套物件 via accepts_nested_attributes_for,但我似乎找不到可行的替代方案。
這是 Rails 的錯誤嗎?如何強制正確的回呼每個操作只觸發一次?
class Blog
has_many :posts
has_many :images
accepts_nested_attributes_for :posts
after_update :destory_existing_images, if: -> { images.any? }
after_commit :create_images, on: [:update, :create], if: -> { images.none? }
private
def destory_existing_images
images.destroy_all
end
def create_screenshots
images.create!(tag: title)
end
end
uj5u.com熱心網友回復:
如果您使用單獨的回呼會更好。用于after_create_commit初始化和after_update_commit更新影像。
您還可以在更新影像之前檢查標題是否更改。Dirty API非常適合,你的情況看起來像if: -> { images.any? && saved_change_to_title? }.
解決方案
class Blog
has_many :posts
has_many :images
accepts_nested_attributes_for :posts
after_create_commit :create_images, if: -> { images.none? }
after_update_commit :update_images, if: -> { images.any? && saved_change_to_title? }
private
def update_images
images.destroy_all
images.create!(tag: title)
end
def create_images
images.create!(tag: title)
end
end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/468132.html
標籤:轨道上的红宝石 红宝石 PostgreSQL 打回来 嵌套的
