Question

I'm trying to return the name of all the roles a user has in the following format:

'rolename1','rolename2','rolename3'

So that I can user the has_all_roles? method from rolify.

I've tried collecting the role names like this:

user.roles(:select => :name).collect(&:name)

But that returns an array:

["rolename1","rolename2","rolename3"]

the has_all_roles? method wants them like this:

user.has_all_roles?('rolename1','rolename2','rolename3')

I'm sure I'm missing something very simple.

Was it helpful?

Solution

Capture the result of the collect to a variable and turn the captured array into a list of arguments.

roles = user.roles(:select => :name).collect(&:name)
user.has_all_roles?(*roles)

OTHER TIPS

Since Rails 5.1 the method user.roles(:select => :name) gives you the follow error:

ArgumentError: wrong number of arguments (1 for 0)

To fix it we can just do @user.roles.pluck(:name).

And if you want a string with the concatenated name coma separeted we can do just @user.roles.pluck(:name).join(", ")

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