RolifyCommunity / rolify

Role management library with resource scoping
https://rolifycommunity.github.io/rolify/
MIT License
3.16k stars 404 forks source link

Not creating roles after create user: Rails - 6 & MongoDB - v4.2.3 #533

Open NeelTandel-BTC opened 4 years ago

NeelTandel-BTC commented 4 years ago

here are my user and role model.

class User include Mongoid::Document include Mongoid::Timestamps after_create :assign_default_role rolify devise :database_authenticatable, :registerable, :recoverable, :validatable

field :email, type: String, default: '' field :encrypted_password, type: String, default: ''

field :reset_password_token, type: String field :reset_password_sent_at, type: Time

def assign_default_role add_role(:newuser) if roles.blank? end end

class Role include Mongoid::Document has_and_belongs_to_many :users belongs_to :resource, :polymorphic => true

field :name, :type => String

index({ :name => 1, :resource_type => 1, :resource_id => 1 }, { :unique => true})

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

scopify end

user-created successfully with roles_ids but we can not find any user_roles collection or roles collections in DB.

any suggestions?

SaimonL commented 4 years ago

Not sure if this helps but starting in Rails 5 and up you have to have two way model association which is required. If you don't want that then you must specify "optional" option.

In "role.rb" belongs_to :resource, polymorphic: true, optional: true

To me this gem is considered broken for Rails 5 and up unless they mention this above. Rolify is working for me in Rails 5.2.4.2 using MongoID 6.

This is how my role.rb looks like

class Role
  include Mongoid::Document
  include Mongoid::Timestamps

  has_and_belongs_to_many :users
  belongs_to :resource, polymorphic: true, optional: true

  field :name, type: String

  index({
    name: 1,
    resource_type: 1,
    resource_id: 1
  },
  { unique: true})

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

  scopify
end

Make sure that the user model has "rolify" mentioned

SaimonL commented 4 years ago

Just tested in mongoid (7.0.8) and it works given you set "optional: true" as mentioned above.