R
R
rail01y2017-04-08 20:24:11
Ruby on Rails
rail01y, 2017-04-08 20:24:11

How to correctly make a link in the_role gem?

Good day, I'm trying to make a bunch of the_role + devise + the_role_dashboard gem, and in particular, I ran into a problem in a bunch of one user - several roles. The roles seem to be set, but at the same time I don’t have access to the dashboard (cut learn on the fly, don’t scold strictly)
routes.rb

Rails.application.routes.draw do
  TheRoleManagementPanel::Routes.mixin(self)
  devise_for :users
  resources :dashboard, only: [:index]
  root 'home#index'
end

models/user.rb
class User < ApplicationRecord
  include TheRole::Api::User
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :user_roles
  has_many :roles, :through => :user_roles

  def role?(role)
    roles.any? { |r| r.name.underscore.to_sym == role }
  end

end

models/user_role.rb
class UserRole < ApplicationRecord
  belongs_to :user
  belongs_to :role
end

modes/role,rb
class Role < ActiveRecord::Base
  include TheRole::Api::Role
  has_many :user_roles
  has_many :users, :through => :user_roles
end

the_role config itself which is in initial

config.login_required_method = :authenticate_user!
config.layout = :the_role_management_panel
config.layout_title = 'M2 Role Controller'

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Leonchik, 2017-04-10
@rail01y

I must say right away that I didn’t use this gem, but I’ll write how you can do it differently, it will suddenly come in handy ... The
example below describes how you can implement a simple role or a role for a "company"
Model Role

class Role < ApplicationRecord
  belongs_to :user
  belongs_to :company, optional: true

  validates :user, :name, presence: true
  enum name: %i[admin manager]
end

And for example an excerpt from the User model
has_many :roles, dependent: :destroy

def create_role(role_name, company = nil)
  roles.create(name: Role.names[role_name], company: company)
end

def role?(role_name, company = nil)
  if company.present?
    roles.where(name: Role.names[role_name], company: company).any?
  else
    roles.where(name: Role.names[role_name]).any?
  end
end

def admin?
  role? 'admin'
end

def manager?(company)
  role? 'manager'
end

Further everything is simple
# Fake
user = User.first
company = Company.first

Create an administrator role: Create a company owner role: Check the administrator role: Check the role for the company: And you can restrict access "by roles" with a simple gem pundit Perhaps it was sealed somewhere, I wrote it by hand

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question