2

我将Rails 嵌套属性allow_destroy: true. 如果我这样称呼:

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

并且deck_itemwith id1000不存在 Rails 引发异常ActiveRecord::RecordNotFound

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

4

2 回答 2

1

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
于 2020-03-20T14:50:10.133 回答
0

您始终可以使用 begin rescue 来处理此类异常

begin
  deck.update(deck_items_attributes: { id: 1000, _destroy: true })
rescue ActiveRecord::RecordNotFound => e
  puts custom_error_msg
end
于 2020-03-20T12:32:12.143 回答