Search code examples
ruby-on-railsrubyactiverecordrolify

ActiveRecord::RecordInvalid: Validation failed: Resource type is not included in the lis


I am new to rails.I am using rolify gem for adding user roles. I am getting this problem when I am trying to add a role from rails console. Does any have faced this problem ?

u = User.first
u.add_role(:admin).save!

error list ===

ActiveRecord::RecordInvalid: Validation failed: Resource type is not included in the list.

Rolify migration file ============

class RolifyCreateRoles < ActiveRecord::Migration
def change
create_table(:roles) do |t|
t.string :name
t.references :resource, :polymorphic => true
t.timestamps
end

create_table(:users_roles, :id => false) do |t|
  t.references :user
  t.references :role
end

add_index(:roles, :name)
add_index(:roles, [ :name, :resource_type, :resource_id ])
add_index(:users_roles, [ :user_id, :role_id ])

end
end`

I have followed the documentation for installing rolify from here == https://github.com/RolifyCommunity/rolify


Solution

  • It seem that in version 3.5, it is not possible to create global role as happening in previous version. Actually whenever Role get created, it need resource_type, currently since you are creating global role which does not have any resource, its throwing errors. But if you create role on instance it will work. Consider you have some model named 'Post' as

    Class Post
      resourcify 
    end
    On Rails console, create 
    user = User.first
    user.add_role(:admin, Post.first)
    

    As i have given above scenerios, when i create role, it will get resource_type as 'Post'. But in your case, role does not getting resource_type. So if you want to create global role, then better would be remove ' validates :resource_type, :inclusion => { :in => Rolify.resource_types } ' from your 'role' model