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 s
At first, if your users table has foreign key account_id then you need to use
class User
belongs_to :account
end
In this way you will ensure that User can be associated just to one Account.
If you want to limit that Account can have e.g. at most 3 users then you can define the following validation:
class User
validates_each :account do |user, attr, value|
user.errors.add attr, "too much users for account" if user.account.users.size >= 3
end
end
and as a result you will not be able to create new user for account if account has already 3 users.