【发布时间】:2026-01-23 04:15:01
【问题描述】:
我有一个 Account 模型和一个 User 模型:
class Account < ActiveRecord::Base
has_many :users
end
class User < ActiveRecord::Base
belongs_to :account
end
用户属于一个帐户,一个帐户有一个用户上限(每个帐户不同)。但是,在向帐户添加新用户时,如何验证尚未达到此最大值?
首先我尝试对用户添加验证:
class User < ActiveRecord::Base
belongs_to :account
validate :validate_max_users_have_not_been_reached
def validate_max_users_have_not_been_reached
return unless account_id_changed? # nothing to validate
errors.add_to_base("can not be added to this account since its user maximum have been reached") unless account.users.count < account.maximum_amount_of_users
end
end
但这只有在我一次添加一个用户时才有效。
如果我通过@account.update_attributes(:users_attributes => ...) 添加多个用户,即使只有一个用户的空间,它也会直接通过。
更新:
澄清一下:当前的验证方法验证account.users.count 小于account.maximum_amount_of_users。比如说account.users.count 是 9,account.maximum_amount_of_users 是 10,那么验证就会通过,因为 9
问题是从account.users.count 返回的计数在所有用户都写入数据库之前不会增加。这意味着同时添加多个用户将通过验证,因为在所有用户都通过验证之前,用户数都是相同的。
所以正如 askegg 指出的那样,我是否也应该向 Account 模型添加验证?那应该怎么做呢?
【问题讨论】:
标签: ruby-on-rails validation activerecord