限制has_many关系中关联数的最佳实践? [英] Best practice for limiting the number of associations within a has_many relationship?

查看:62
本文介绍了限制has_many关系中关联数的最佳实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个模型-用户和帐户。每个帐户最多可以与n个用户相关联,并且一个用户只能与一个帐户相关联。

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.

说用户

belongs_to :account

和帐户

has_many :users

但是,我不清楚最佳做法是什么时候通过has_many声明限制关联的数量。我知道有一个:limit参数,但这仅限制了返回的关联数,而不是能够存在的关联数。

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.

我怀疑答案是是使用类似:before_add的东西。但是,该方法似乎仅适用于通过<<< 。因此,当您使用

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 

但如果您使用

@account.users.create

我也考虑过在用户模型中使用before_save来实现限制可能更实际,但是在用户模型中实现帐户业务规则似乎有点困难。

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?

编辑:每个帐户的n个用户将是一些存储在各个帐户中的业务数据,而不是

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.

推荐答案

首先,如果您的users表中有外部表,密钥account_id,那么您需要使用

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.

如果您想限制该帐户可以拥有例如最多3个用户,则可以定义以下验证:

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

,因此,如果帐户已有3个用户,则将无法为该帐户创建新用户。

and as a result you will not be able to create new user for account if account has already 3 users.

这篇关于限制has_many关系中关联数的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆