Skip to content

The correct way to use after_save callback with self-defined error message. #1886

Answered by jwoertink
zw963 asked this question in Q&A
Discussion options

You must be logged in to vote

I'm not completely clear on what the issue is, but when you use after_save you are still inside of the initial database transaction. So you can call database.rollback which will un-do the original object save.

after_save code_and_batch_level_must_uniq

def code_and_batch_level_must_uniq(saved_record : University)
  code.value.try do |code_value|
    if not_unique_code
       code.add_error("must be unique")
       database.rollback  # this line will un-save the university record
     end
  end
end

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@zw963
Comment options

Answer selected by zw963
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants