Skip to content

Instantly share code, notes, and snippets.

@vmarcetic
Created July 21, 2013 20:51
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save vmarcetic/6049929 to your computer and use it in GitHub Desktop.
Save vmarcetic/6049929 to your computer and use it in GitHub Desktop.
Better view of article on coderwall
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
if User.current_role == 'admin' # From ApplicationController we can get current_role and check it up against the role we want.
can :manage, :all
else
if User.current_role == 'moderator'
can :read, Products
can :update, Products
cannot :destroy, Products
cannot :create, Products
cannot :manage, Client
end
can :read, :all
end
end
end
class ApplicationController < ActionController::Base
before_filter :initialize_company, :initialize_user_role
# we find company that user currently uses and we store data in class ( cattr_accessor :current)
def initialize_company
Company.current = Company.find(params[:company_id]) if params.has_key?(:company_id)
end
# we find user role for companie that he is managing and we store data in class ( cattr_accessor :current_role )
def initialize_user_role
User.current_role = Unity.where(company_id: Company.current.id, user_id: current_user.id).first.role.name unless Company.current.nil?
end
end
class Company < ActiveRecord::Base
cattr_accessor :current # here I added a current company, so I can check wich company is active I will use that later.
has_many :unities
has_many :users, through: :unities
has_many :roles, through: :unities
end
create_table :unities do |t|
t.integer :role_id
t.integer :user_id
t.integer :company_id
t.timestamps
end
class Role < ActiveRecord::Base
has_many :unities
has_many :users, through: :unities
has_many :companies, through: :unities
end
class Unity < ActiveRecord::Base
attr_accessible :role_id, :user_id, :company_id
belongs_to :role
belongs_to :company
belongs_to :user
end
class User < ActiveRecord::Base
rolify
cattr_accessor :current_role # I added current_role so I can check which role does user haves on a company that he is on but I will get to that later
has_many :unities
has_many :roles, through: :unities
has_many :companies, through: :unities
end
@jasper502
Copy link

Question: How did you handle the registration for this example? Did you use the Devise stock sign-up and nest the company / roles in or create the company and then the user / role?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment