简体   繁体   English

如何获取current_user的用户角色的信息

[英]how get user roles's slug in rails for the current_user

I have a roles based authentication with devise gem; 我有一个基于devise gem的基于角色的身份验证; all users can has many roles and how can i retrieve just user role slug for the current_user? 所有用户都可以有许多角色,我如何才能仅检索current_user的用户角色?

now in my User.rb model i have created a method called get_role 现在在我的User.rb模型中,我创建了一个名为get_role的方法

User.rb User.rb

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

i call this method in a view like that 我在这样的视图中调用此方法

current_user.get_role

and it returns this: 它返回此:

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

why if a call an each block in that method? 为什么要在该方法中调用每个块? Thanks 谢谢

Use map ( doc for map method ) instead of each ( doc for each method ): 使用mapmap方法为doc ),而不是each map每个方法为doc ):

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

When you iterate a collection with each the returned value will be the collection itself. 当您对each集合进行迭代时,返回值将是集合本身。 each iterator is for doing something with each element. each迭代器用于对每个元素做某事。 And it's property allow you to write chains of each method calls: 它的属性允许您编写each方法调用的链:

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

Not very smart example, because we may do just: 这不是一个非常聪明的例子,因为我们可能会做:

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

But just as an example. 但仅作为示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM