If you have an ActiveRecord object you need to perform some operation on before validating and saving it to the database, you would normally use the ActiveRecord Callbacks. But which callback to use might be a bit misleading for some, as it happened to me.
For my case, I needed to perform some trimming on a string, let’s call it name here, before sending it for validation and saving it. I looked at the before_save callback and thought that’s it. But that was not the case, for then, duplicate values were allowed in. Why? It’s because before_save callback is called after before_validation. So this is what was happening:
before_validation: #(nothing called here) before_save: trim_name #(Name is changed now) save()
Obviously, what was validated is not what was inserted, and hence, to my disliking, I was getting duplicate names in the database. Solution ofcourse is to use the before_validation callback if you are altering the data and need to validate it.