How to debug inside a code block without skipping it

169 views Asked by At

I'm attempting to debug my code, in order to see if @new_participant is instantiated, but when I place binding.pry around it as displayed below, it hops over the block, and placing the debugger within the block obviously doesn't work either. How do I debug this?

 def create_participant!(case_file)
     binding.pry
      params = participant_params(case_file.case_file.id)
      ActiveRecord::Base.transaction do
        @new_participant = participant_clazz.create!(params)
        assign_private_infos!(participant_id: new_participant.id)
     binding.pry
      end
      call_link_participant_job!
    end
1

There are 1 answers

0
max On

You're calling create! which will raise an ActiveRecord::RecordInvalid exception if the record is not valid. Exceptions immediately halt the script execution and Ruby goes up the call stack until a rescue is found (or not).

ActiveRecord::Transactions wraps the block in a rescue which triggers a rollback and then propagates the exception.

Also have in mind that exceptions thrown within a transaction block will be propagated (after triggering the ROLLBACK), so you should be ready to catch those in your application code.

If you want to run code before the rollback you need to rescue the exception inside the block:

def create_participant!(case_file)
  binding.pry
  params = participant_params(case_file.case_file.id)
  ActiveRecord::Base.transaction do
    begin 
      @new_participant = participant_clazz.create!(params)
      assign_private_infos!(participant_id: new_participant.id)
    rescue ActiveRecord::RecordInvalid => e 
      binding.pry
      raise e # re-raise the exception to trigger a rollback
    end
    call_link_participant_job!
  end
end

Or you can rescue the exception after the rollback:

def create_participant!(case_file)
  binding.pry
  params = participant_params(case_file.case_file.id)
  
  begin
    ActiveRecord::Base.transaction do
      @new_participant = participant_clazz.create!(params)
      assign_private_infos!(participant_id: new_participant.id)
      call_link_participant_job!
    end
  rescue ActiveRecord::RecordInvalid => e 
    binding.pry
  end
end