0

I have a while do loop in rails as

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

For each execution of the loop, I try to create and save a speaker and sometimes there raises an exception in the active_record (due to non-availability of the image file or 403 forbidden exception etc).

I would want to catch that in my rescue block and process it further. However, the exception is caught and rescued elsewhere (within the active_record) which throws an exception in my console directly, and hence the code won't reach my 'rescue' block at all. However, my code reaches 'ensure' block.

How do I change my code to reach my 'rescue' block?

Vishnukk
  • 524
  • 2
  • 11
  • 27
  • Don't use rescue without specifying what exceptions you are rescuing. It creates a black hole that will mask bugs and make debugging impossible. https://stackoverflow.com/a/35121040/544825 – max May 06 '20 at 13:23

1 Answers1

1

You're looking for find_or_create_by!

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

Lots of active record methods will fail simply by returning false (save, update, create etc..), but will throw an error when an exclamation mark gets added at the end

Mark
  • 6,112
  • 4
  • 21
  • 46