Limiting object counts in rails associations
Let's say you have a model owner
and a model pet
. Every owner has_many
pets, but you want to limit the number of pets an owner can have. You can use the following validation in your model to make sure these owners don't get greedy with their number of pets.
has_many :pets
validates :pets, length: { maximum: 5 }
The length
helper is telling rails to only allow an owner to have a maximum of 5 pets. This is a little awkward because the length helper usually pertains to enforcing a minimum or maximum length on a string attribute, but it still works on the ActiveRecord Association Collection of :pets
in a similar way where it is basically validating the maximum size of the collection.