Sazzad
Sazzad

Reputation: 853

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

Upvotes: 2

Views: 2909

Answers (4)

webaholik
webaholik

Reputation: 1815

You need to allow resource_type to be nil on your Role Model.

For Rails 4, we had this in our Role model:

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

Starting in Rails 5, belongs_to association required by default, which is where optional: true comes in:

belongs_to :resource, :polymorphic => true, optional:true
validates :resource_type,
        :inclusion => { :in => Rolify.resource_types },
        :allow_nil => true

Upvotes: 0

Sanjiv
Sanjiv

Reputation: 843

@Sazzad Please change the role model as given below:

class Role < ActiveRecord::Base 
  has_and_belongs_to_many :users, :join_table => :users_roles belongs_to :resource, :polymorphic => true 

  scopify 
end

Upvotes: 0

Sanjiv
Sanjiv

Reputation: 843

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

Upvotes: 1

Sanjiv
Sanjiv

Reputation: 843

Version >= 3.5 has these issue, for time being use version rolify 3.4. I will fixed and send then pull request.

Upvotes: 0

Related Questions