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)
سؤال
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.
المحلول
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)
نصائح أخرى
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(", ")