如何在current_user的rails中获取用户角色的slug

时间:2013-02-21 10:35:01

标签: ruby-on-rails ruby authentication devise roles

我有一个基于角色的认证与设计宝石;所有用户都可以拥有多个角色 我怎样才能检索current_user的用户角色slug?

现在在我的User.rb模型中,我创建了一个名为get_role

的方法

User.rb

def get_role
  roles.each { |role| role.slug.downcase }
end

我在类似的视图中调用此方法

current_user.get_role

然后返回:

[#<Role id: 3, name: "Seller", created_at: "2013-01-10 21:04:46", updated_at: "2013-01-10 21:04:46", slug: "Venditore">]

为什么在该方法中调用每个块? 感谢

1 个答案:

答案 0 :(得分:1)

使用mapdoc for map method)代替eachdoc for each method):

def get_role
  roles.map { |role| role.slug.downcase }
end

使用each迭代集合时,返回的值将是集合本身。 each迭代器用于对每个元素执行某些操作。它的属性允许您编写each方法调用链:

workers.each{ |w| w.take_a_break }.each{ |w| w.just_joke_go_to_work }

不是很聪明的例子,因为我们可能只做:

workers.each{ |w| w.take_a_break; w.just_joke_go_to_work }

但仅作为一个例子。