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

问题描述 投票:0回答:1

我正在将Rails nested attributesallow_destroy: true一起使用。如果我打这样的话:

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

且ID为deck_item1000不存在,Rails引发异常ActiveRecord::RecordNotFound

有没有办法告诉Rails不要抛出异常而只是忽略该记录?

ruby-on-rails ruby nested-attributes accepts-nested-attributes
1个回答
0
投票

您总是可以使用begin抢救来处理这种类型的异常

begin
  deck.update(deck_items_attributes: { id: 1000, _destroy: true })
rescue ActiveRecord::RecordNotFound => e
  puts custom_error_msg
end
© www.soinside.com 2019 - 2024. All rights reserved.