不确定如何在用户上使用计划验证器来检查计划是否达到最大允许用户数 Rails 4 设计可邀请

Not sure how to approach using a Plan Validator on User to check if the Plan is at max allowable users Rails 4 Devise Invitable

我在 Rails 4 中使用公寓 Gem 构建了一个多租户应用程序,这是一个基于订阅的应用程序,并通过计划类型限制用户数量。

我的计划模型中有以下验证(我将在此处粘贴整个内容),但我不确定如何验证它,以便管理员或所有者无法邀请用户(如果帐户位于最大容量?

Plan.rb:

class Plan < ApplicationRecord
  # Enum & Constants
  enum plan_type: [:responder, :first_responder, :patrol_pro, :guardian]

  USER_LIMITS = ActiveSupport::HashWithIndifferentAccess.new(
    #Plan Name      #Auth Users
    responder:        6,
    first_responder:  12,
    patrol_pro:       30,
    guardian:         60
  )

  # Before Actions

  # Relationships
  belongs_to :account, optional: true

  # Validations
  validate :must_be_below_user_limit

  # Custom Methods
  def user_limit
    USER_LIMITS[self.plan_type]
  end

  def must_be_below_user_limit
    if account.present? && persisted? && User.count < user_limit
     errors[:user_limit] = "can not more than #{user_limit} users"
   end
  end

end

功能方面我想确保所有者在关联帐户的用户数超过 plan_type 允许的情况下无法添加用户。如果是这样我想闪一条消息说请升级..

提前致谢..这是我存在的祸根!!

您为 user_limit 采取了错误的条件并删除了持久化?它不需要,因为你已经采取了,account.present?

class Plan < ApplicationRecord
  # Enum & Constants
  enum plan_type: [:responder, :first_responder, :patrol_pro, :guardian]

  -----------------------

  # Custom Methods
  def user_limit
    USER_LIMITS[self.plan_type]
  end

  def must_be_below_user_limit 
    if account.present? && (account.users.count > user_limit)
     errors.add(:user_limit, "can not more than #{user_limit} users") 
    end
  end 

end