2

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.

4

2 回答 2

4

将收集的结果捕获到变量中,并将捕获的数组转换为参数列表。

roles = user.roles(:select => :name).collect(&:name)
user.has_all_roles?(*roles)
于 2013-04-18T22:22:41.153 回答
0

从 Rails 5.1 开始,该方法user.roles(:select => :name)会为您提供以下错误:

ArgumentError: wrong number of arguments (1 for 0)

要修复它,我们可以这样做@user.roles.pluck(:name)

如果你想要一个串联名称逗号分隔的字符串,我们可以这样做@user.roles.pluck(:name).join(", ")

于 2018-10-08T20:11:53.810 回答