Take the 2-minute tour ×

I have a rails application where I have set up a table: users another table: roles and finally a join table: user_roles where a user may have many roles, but a role belong_to_and_has_many :users

This has allowed me to create new roles and then, assuming thee user is an admin, on the user edit page, switch their role.

This is great, how ever currently no role has capabilities. What I was thinking was doing:

  • role_permissions table
  • permissions: has_and_belongs_to_many :roles
  • Setting up a set of checkboxes on the roles edit page to assign a set of capabilities to said role, that can then be applied to said user, that can then be used by capybara to determine if a user has the appropriate action or not.

While you can create roles, you cannot create capabillities. so you would have a predetermined list of capabilities. Also some roles, such as administrator or member could not be destroyed or edited. (already done.)

I can set up the table and the relationship to do this, what I cannot figure out how to do is to integrate this concept with cancan. Because can can does something like:

can? :destroy @project

If I assign, say:

Role: Editor (String name) Capabilities: Read, Write, Destroy, Update, Preview (These are just string names)

How could I then say:

can? user.role? Editor read Post - seudo code.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

First of all, for capabilities, if it's a fixed list of capabilities you're working with, you're probably better off with having a number of booleans on the roles table, e.g. can_create_projects, can_create_users, etc., which encode the abilities of each role.

Then your CanCan Ability class might have something like the following,

class Ability
  include CanCan::Ability

  def initialize(user)
    can(:create, Project) do |project|
share|improve this answer

Your Answer


