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

后端 未结 2 2033
小蘑菇
小蘑菇 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.

提交回复
热议问题