0

I am having rails 4 application with user, role, permissions implemented using Pundit gem. I have 3 models user, role, roles_users as I have many_to_many relation between user and role. I want to edit the user roles.

class User
  has_and_belongs_to_many :roles
end

class role
  has_and_belongs_to_many :users
end

A 3rd table roles_users that stores user_id and role_id.

So suppose I want to edit a user role, what approach should I follow. Should I delete the existing records from 3rd table i.e roles_users and then create new record showing role. Please suggest.

Sachin Kadam
  • 265
  • 2
  • 12

1 Answers1

2

Not sure if you're still working on this or what you're exactly trying to accomplish, but a good way to go around handling user roles with pundit is working with devise to handle user profiles and create an admin account. The admin would be able to change a specific user's role to whatever role you have as an option (i.e. user, vip, moderator, editor, admin, etc.). The sky is the limit in how complex you want your app to be with multiple roles. The use of "enum" in your user model will help guide your role options:

class User < ActiveRecord::Base

  enum role: [:user, :vip, :admin]
  after_initialize :set_default_role, :if => :new_record?

  def set_default_role
    self.role ||= :user
  end

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

end

This way you can set the default role of a new user to be a regular user and then the admin can update the user to whatever role the new user should be. This should be able to be worked into multitennant applications if you wanted a more complex app with multiple companies/groups. Pundit policies and scopes will then come into play to determine who has authorization to do certain actions within your app. For example:

  • an admin can see a list of users
  • an admin can change a user’s role
  • an admin and editor can create, edit, delete, update a blog post
  • an ordinary user can’t see a list of users
  • an ordinary user can’t change their role
  • an ordinary user can’t see (or edit) another user’s profile
  • an ordinary user can see (and edit) their own user profile
  • an ordinary user can't edit, delete, or update a blog post
  • an ordinary user can see published blog posts

A great resource to get started is to follow along in the Rails-devise-pundit sample application that will walk you through getting things set up pretty well with user roles. If you're more visual, you can follow along with this YouTube video: Rails Authorization with Pundit. This video is great if you're also looking to test with rspec as you create your user roles.

Hopefully this steers you in the correct direction of what you're trying to accomplish.

Nate
  • 71
  • 8