Rolify gem (user.add_role :admin ArgumentError: Unknown key: :optional)

Maybe you tried to add a role using rolify, like below:

$ user = User.find(1)
$ user.add_role :admin

Then you got an error like:

ArgumentError: Unknown key: :optional. Valid keys are: :class_name, :class, :foreign_key, :validate, :autosave, :dependent, :primary_key, :inverse_of, :required, :foreign_type, :polymorphic, :touch, :counter_cache

The rolify generator generates Role model like:

class Role < ActiveRecord::Base


has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true,
             :optional => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end  

The :optional => true parameter is supported in Rails version 5 and above.

To fix this issue or get around it, just delete that line I mentioned above like this:

class Role < ActiveRecord::Base  
  has_and_belongs_to_many :users, :join_table => :users_roles

  belongs_to :resource,
             :polymorphic => true

  validates :resource_type,
            :inclusion => { :in => Rolify.resource_types },
            :allow_nil => true

  scopify
end  

Now you can re-try:

$ user.add_role :admin

Then you are good to go, you will see something like:

=> #<Role id: 1, name: "admin", resource_id: nil, resource_type: nil, created_at: "2016-09-23 07:07:10", updated_at: "2016-09-23 07:07:10">

Victor Velazquez

Coder, Musician, Startups, Passionate Dancer & Life Lover. Software Engineer at MagmaLabs, Co-founder of Web Dev Talks, Co-founder of Voltaire, Co-founder of Paqkit, Ex-co-founder of Zaznova.

Subscribe to The zazvick's blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!