Say that I have two models- Users and Accounts. Each account can have at most n users associated with it, and a user can only be associated with one account.
It would seem natural to say that User
belongs_to :account
and Account
has_many :users
However, I'm not clear on the best practice when it comes to limiting the number of associations through that has_many declaration. I know that there is a :limit argument, but that that only limits the number of associations returned, not the number that are able to exist.
I suspect that the answer is to use something like :before_add. However, that approach seems only to apply to associations created via << . So it would get called when you used
@account.users << someuser
but not if you used
@account.users.create
I had also considered that it might be more practical to implement the limit using before_save within the User model, but it seems like it would be a bit off to implement Account business rules within the User model.
What is the best practice for limiting the number of associations?
Edit: the n users per account would be some business data that is stored within the individual accounts, rather than being a straight up magic number that would be floating around willy nilly in the code.