'Devise Invitable, how to set invitation_limit according to user in Rails

I would like to control the number of invitations per user

I know that I can make some configurations to devise_invitable in my config/initializers/devise.rb file, and limit how many users I want to invite for example:

# initializer/devise.rb
# Number of invitations users can send.
... 
config.invitation_limit = 5

But I want is that depending on the type of user I can invite more or less people.

If I have a role type administrator then it would be something like config.invitation_limit = 10

If I have a common user role then I can invite only 3 people and so respectively



Solution 1:[1]

The documentation states:

You can change invitation_limit column for some users so they can send more or less invitations...

You could set the invitation_limit on create.

class User < ApplicationModel
  before_create :set_invitation_limit
  
  def initial_invitation_limit
    if is_admin?
      10
    else
      3
    end
  end

  def set_invitation_limit
    self.invitation_limit = initial_invitation_limit
  end
end

If you allow changes to the role after creation you may use before_save.

Or you could override the invitation_limit method:

class User < ApplicationModel
  def initial_invitation_limit
    if is_admin?
      10
    else
      3
    end
  end

  def invitation_limit
    self[:invitation_limit] || initial_invitation_limit
  end
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dario