Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Stopping event without raising from after callback #835

Open
paulodeon opened this issue Jul 18, 2023 · 1 comment
Open

Stopping event without raising from after callback #835

paulodeon opened this issue Jul 18, 2023 · 1 comment

Comments

@paulodeon
Copy link

aasm column: :status, whiny_transitions: false do
  state :requested, initial: true
  state :approved

  event :approve, after: :after_approve do
    transitions from: :requested, to: :approved
  end
end

def after_approve
  raise "This is a test"
end

Given the above I want to be able to call obj.approve! and still have it return true or false so I can handle the exceptions in the model, add errors to the object and handle it in the controller.

I have tried returning false, error handlers etc but it seems there is no way to stop the event from the after callback without raising, nor is there any way to catch the exception handle it and return false (that I can find).

As a workaround I've had to create a new method which wraps the call to approve!

  def approve_with_errors
    approve!
  rescue StandardError => e
    errors.add(:base, "Error: #{e}")
    false
  end

Is there no way to achieve this in aasm without adding these wrappers?

@paulodeon
Copy link
Author

In Rails in after callbacks you need to raise ActiveRecord::RecordInvalid, self and the callback chain will be aborted but the exception is not passed up the stack. To do the same in before_ callbacks you can throw(:abort)

rails/rails#33192

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant