Search code examples
ruby-on-railsruby-on-rails-4devise-invitableapartment-gem

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


Im building out a multi-tenant app in Rails 4 using the Apartment Gem, this is a subscription based application and limits the number of users by the plan type.

I have the following validation in my Plan Model (I'll paste the whole thing here), but I am unsure of how to validate this so that an admin or owner can not invite a user if the account is at max capacity?

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

Functionality wise I Want to make sure that the owner can not add a user if the user count for the associated account is more than the plan_type allows. if so I Want to flash a message saying please upgrade..

thanks in advance.. This is the bane of my existence!!


Solution

  • You have taken a wrong condition for the user_limit and remove the persisted? its not needed as you have taken, 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