Question

Has anyone tried to add user role switching using the authlogic/declarative authorisation gems?

My requirement is that a user can have many roles (e.g. Author, Teacher) and can switch role within the application.

I have a two ideas of how I might approach this:

  1. Adding another boolean attribute (active), to the user_roles join table
  2. Copying the switched role_id into the users table and working off that

I read the declarative authorisation readme and can't see anything that appears to be built in. Any ideas would be appreciated

Was it helpful?

Solution

Just looked back into this today and the solution is easy enough. I went with adding a boolean attribute to my many-to-many user_roles join to avoid duplication. The join now has the following attributes:

id | user_id | role_id | active

The role_symbols method in my user model, which is used to hook in the authorization_rules.rb DSL now looks like:

def role_symbols
  user_roles.where(:active => true).map do |user_role|
    user_role.role.name.underscore.to_sym
  end
end

Now a users role sets itself to which ever role has active true in the user_roles table.

User switching is easy too (from the user model)

def self.set_active_role(user_id, role_id)
  UserRole.where(:user_id => user_id).update_all(:active => false)

  activate_role = UserRole.where(:user_id => user_id, :role_id => role_id).first
  activate_role.update_attributes(:active => true)
end

Thought it might help someone in the future

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top