Skip to content

Instantly share code, notes, and snippets.

@krisleech
Last active April 24, 2018 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save krisleech/ef9b6493b73cc398e513931ddc3732fe to your computer and use it in GitHub Desktop.
Save krisleech/ef9b6493b73cc398e513931ddc3732fe to your computer and use it in GitHub Desktop.
Wisper and Transaction gotcha
class CreateStudy

  def call(attributes)
    study = Study.new(attributes)

    ActiveRecord::Base.transaction do
      begin
        study.save!
        raise "something bad happens here"
      rescue
        broadcast(:failed, study)
        raise ActiveRecord::Rollback
      else
        broadcast(:successful, study)
        broadcast(:study_created, id: study.id)          
      end
    end
  end
end

When an error occurs after study.create!, because broadcast(:failed, study) is inside the transaction the study object will have an id. Thus to whatever is listening to the failed event will think the study has been persisted because the rollback has not yet occured.

So in a controller is you subscribe to the failed event in order to render the new form again it will have the wrong URL, since it will think it is rendering the form for a persisted model.

@krisleech
Copy link
Author

Note Rollback does not reset the id anyway.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment