I would like to limit the number of items in an association. I want to ensure the User doesn\'t have more than X Things. This question was asked before and the solution had th
Validating on the current count causes the count to become greater than the limit once the save has completed. The only way I've found way to prevent the create from occurring is to validate that before the create, the number of things is less than the limit.
This is not to say that it isn't useful having a validation on the count in the User model, but doing so doesn't prevent User.things.create
from being called because the user's count collection is valid until the new Thing object is saved, and then becomes invalid after the save.
class User
has_many :things
end
class Thing
belongs_to :user
validate :on => :create do
if user && user.things.length >= thing_limit
errors.add(:user, :too_many_things)
end
end
end