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

后端 未结 2 2034
小蘑菇
小蘑菇 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条回答
  • 2021-02-10 17:44

    I think your rule is subject to a different interpretation. Think of the rule as being "You cannot add a user to an account that already has 3 users." Now that it is a user rule, implementing it on the user object seems perfectly natural and @Raimond's solution will suffice.

    You could also think about implementing this as a database constraint, but I probably wouldn't go that way...3 seems to be an arbitrary number that may change later and I, and I suspect you, would prefer that it be captured in the code rather than hidden away in a DB constraint.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题