Skip to content

Instantly share code, notes, and snippets.

@simonlehmann
Forked from vmarcetic/ability.rb
Last active February 23, 2018 15:43
Show Gist options
  • Save simonlehmann/a4f07b9e80eb42ce05da4157552f99b0 to your computer and use it in GitHub Desktop.
Save simonlehmann/a4f07b9e80eb42ce05da4157552f99b0 to your computer and use it in GitHub Desktop.
Rails, Devise, CanCanCan, Rolify and User Group Roles
class Ability
include CanCan::Ability
def initialize(user)
user ||= User.new # This is used for not logged user if you have a need for it
case user.current_role
when 'admin'
can :manage, :all
when 'moderator'
can :read, Products
can :update, Products
cannot :destroy, Products
cannot :create, Products
cannot :manage, Client
# ... other roles and abilities ...
end
end
end
class ApplicationController < ActionController::Base
before_filter :initialize_group, :initialize_user_role
# we find group that user currently uses and we store data in class ( cattr_accessor :current)
def initialize_group
Group.current = Group.find(params[:group_id]) if params.has_key?(:group_id)
end
# we find user role for group that he is managing and we store data in class ( cattr_accessor :current_role )
def initialize_user_role
User.current_role = Unity.where(group_id: Group.current.id, user_id: current_user.id).first.role.name unless Group.current.nil?
end
end
class Group < ActiveRecord::Base
has_many :unities
has_many :users, through: :unities
has_many :roles, through: :unities
cattr_accessor :current # here I added a current group, so I can check wich group is active I will use that later.
end
create_table :unities do |t|
t.integer :role_id
t.integer :user_id
t.integer :group_id
t.timestamps
end
class Role < ActiveRecord::Base
has_many :unities
has_many :users, through: :unities
has_many :groups, through: :unities
end
class Unity < ActiveRecord::Base
belongs_to :role
belongs_to :group
belongs_to :user
attr_accessible :role_id, :user_id, :group_id
end
class User < ActiveRecord::Base
rolify
has_many :unities
has_many :roles, through: :unities
has_many :groups, through: :unities
cattr_accessor :current_role # I added current_role so I can check which role does user haves on a group that he is on but I will get to that later
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment