Rails-在do-while循环内未到达救援块

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

我有一阵子的循环做为

session['SPEAKERS'].map do |speaker|
      begin
        Component::AgendaSpeaker.create_with(
            name: [speaker['FIRST_NAME'], speaker['LAST_NAME']].join(' '),
            job_title: speaker['TITLE'],
            remote_file_url: speaker['PHOTO_URL'],
            description: speaker['EXPERTISE']
        ).find_or_create_by(
            component_id: component_id(:agenda_speakers),
            weg_id: speaker['SPEAKER_ID']
        )
      rescue
        p "Rescue reached"
      ensure
        p "Ensure reached"
      end
    end

对于循环的每次执行,我都会尝试创建并保存一个扬声器,有时在active_record中会引发异常(由于图像文件不可用或403禁止的异常等)。

我想将其捕获在救援区中并进一步处理。但是,该异常是在其他位置(在active_record中)捕获和挽救的,这直接在控制台中引发了异常,因此代码根本不会到达我的“ rescue”块。但是,我的代码到达了“确保”块。

如何更改代码以到达“救援”区?

ruby-on-rails exception activerecord do-while rescue
1个回答
0
投票

您正在寻找find_or_create_by!

https://apidock.com/rails/ActiveRecord/Relation/find_or_create_by%21

许多活动记录方法将仅通过返回false(保存,更新,创建等)而失败,但是在结尾添加感叹号时将引发错误

© www.soinside.com 2019 - 2024. All rights reserved.