Search code examples
ruby-on-railsrolify

Rolify Assign Multiple User Roles at Once


For the Rolify gem in Rails in order to add a role to a user you can do:

user = User.find(1)
user.add_role :admin

But I have a large database of already existing users with no roles. How do I add a role to multiple users with a single command?

I tried the snippet below but it errored:

users = User.where(email:['email1','email2'])
users.addrole :admin

Does anyone know how to do this? Or do I need to create a script that cycles through the users automatically and assigns a role one by one?


Solution

  • Rolify is mostly just a quick and dirty role system, and it currently doesn't provide this feature.

    You'll have to write a bulk insert/upsert query of your own into the database tables that Rolify persists data, e.g. (roles and users_roles for a users table).