Best practice for limiting the number of associations within a has_many relationship?

后端 未结 2 2031
小蘑菇
小蘑菇 2021-02-10 17:41

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

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-10 17:53

    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.

提交回复
热议问题