gpt4 book ai didi

ruby-on-rails - 如果标记为销毁的嵌套属性不存在,则不要引发 ActiveRecord::RecordNotFound

转载 作者:行者123 更新时间:2023-12-05 06:19:42 28 4
gpt4 key购买 nike

我正在使用 Rails nested attributes使用 allow_destroy: true。如果我这样调用:

deck.update(deck_items_attributes: { id: 1000, _destroy: true })

并且 ID 为 1000deck_item 不存在 Rails 引发异常 ActiveRecord::RecordNotFound

有什么方法可以告诉 Rails 不要抛出异常并忽略该记录吗?

最佳答案

如果记录不存在,使用 reject_if: 选项删除属性散列:

accepts_nested_attributes_for :deck_items,
reject_if: :deck_item_does_not_exist?

private
def deck_item_does_not_exist?(attributes)
if attributes["id"].present? && attributes["_destroy"].present?
DeckItem.where(id: attributes["id"]).none?
else
false
end
end

关于ruby-on-rails - 如果标记为销毁的嵌套属性不存在,则不要引发 ActiveRecord::RecordNotFound,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60772796/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com