在Rails的救援块中捕获密钥

时间:2020-07-30 08:46:04

标签: ruby-on-rails ruby exception

我在这里为下面的问题陈述寻找简单的解决方案:

我有很多这样的哈希值:

arr = [
  {group_id: 51, product_id: 34345},
  {group_id: 45, product_id: 22133},
  {group_id: 90, product_id: 10045},
  {group_id: 2,  product_id: 15495},
  {group_id: 23, product_id: 25085}
]

我正在基于BULK INSERTgroup_id的唯一索引运行product_id查询,

GroupProduct.insert_all(arr, unique_by: %i[ group_id product_id ])

此插入语句有时会引发错误ActiveRecord::InvalidForeignKey

PG :: ForeignKeyViolation:错误:在表“ group_products”上进行插入或更新违反了外键约束“ fk_rails_a3bed1e3ad”详情:表(group_products)中不存在键(product_id)=(15495)。

因此,我想在insert_all块内执行begin-resuce操作,这样,如果未找到/存在键product_id,它将重建数组并重试。

基本上,我想在救援区中捕获product_id

这就是我要完成的事情:

arr = [
  {group_id: 51, product_id: 34345},
  {group_id: 45, product_id: 22133},
  {group_id: 90, product_id: 10045},
  {group_id: 2,  product_id: 15495},
  {group_id: 23, product_id: 25085}
]

begin
  GroupProduct.insert_all(arr, unique_by: %i[ group_id product_id ])
rescue ActiveRecord::InvalidForeignKey => e
  arr = arr.reject {|r| r[:product_id] == PRODUCT_ID_I_WOULD_LIKE_TO_CAPTURE}
  retry
end

是否有直接方法让product_ide.message.product_id

1 个答案:

答案 0 :(得分:1)

begin
  GroupProduct.insert_all(arr, unique_by: %i[ group_id product_id ])
rescue ActiveRecord::InvalidForeignKey => e
  match_on_product_it = /\APG::ForeignKeyViolation:.+\(product_id\)=\((\d+)\)/.match e.message
  arr = arr.reject {|r| r[:product_id] == match_on_product_it[1].to_i}
  retry
end