For the purpose of this article, we shall consider a Rails application that includes a model for organizations and a model for users. Each organization can have many users. Furthermore, we shall limit the number of users and organization can have.
There are a handful of strategies to accomplish this, but today let’s explore how association callbacks can solve the situation described above. These callbacks hook into the life cycle of Active Record objects, allowing to work with those objects at various points. More specifically, the before_add callback can be used to ensure the number of users in an organization is bellow the limit, preventing the object from being saved to the database if not.
By causing the before_add callback to throw an exception, the user object does not get added to the collection.
However, this approach comes with a caveat. As association callbacks are triggered by events in the life cycle of a collection, these are called only when the associated objects are added or removed through the association collection.
The following triggers the before_add callback:
On the othet hand, the following does not trigger the before_add callback: