Devise and Rolify - 显示所有用户 - 角色 - 多个角色

Devise and Rolify - Display all of users - roles -- Multiple Roles

我有一个显示用户和角色的视图。我可以用 user.roles.first.name 显示所有用户和一个角色。 我无法让它循环并检索所选用户的所有角色。 任何帮助都会很棒。

<div class="snippet" data-lang="js" data-hide="false">
<div class="snippet-code">
<pre><code>    <h1>Admin#users</h1>
    <p>Find me in app/views/admin/users.html.erb</p>
    <ul>
      <table class="table-bordered col-md-6 ">
      <% @users.each do |user| %>
          <tr>
            <td><%= link_to user.email, edit_user_path(user) %></td>
#guess a loop here .. unable to find how to show all of a users roles.
            <td><%= user.roles.first.name %></td>
# end loop
            <td><%= user.id %></td>
          </tr>
      <% end %>
      </table>
    </ul>

管理员:

    class AdminController < ApplicationController
      before_action :authenticate_user!
      authorize_resource :class => AdminController
      def dashboard
        @user = current_user
      end

      def users
        @users = User.all

      end
    end

用户class:

    class User < ActiveRecord::Base
      rolify

      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable

      # Setup accessible (or protected) attributes for your model

     end

角色class:

    class Role < ActiveRecord::Base
      has_and_belongs_to_many :users, :join_table => :users_roles
      belongs_to :resource, :polymorphic => true

      validates :resource_type,
                :inclusion => { :in => Rolify.resource_types },
                :allow_nil => true

      scopify
    end

找到了一种方法来处理集合。代码如下

views/users/index.html.erb

<table class="table">
  <td>Email</td>
  <td>Role(s)</td>
  <td>Edit</td>
  <td>Delete</td>

<% @users.each do |u| %>
    <tr>

      <td><%= "#{u.email}" %></td>

    <% joinroles = u.roles.collect{|r| r.name} %>
    <td> <%= joinroles.join(" ") %> </td>
     <!-- <td><%= "#{u.roles.collect{|r| r.name}}" %></td>-->
      <td><%= link_to_if(can?(:edit, User), "edit", edit_user_path(u.id)) {} %></td>
      <td><%= link_to_if(can?(:delete, u), "delete", u, :confirm => "Are you sure?", :method => :delete) {} %></td>

    </tr>
<% end %>
</table>

我为此使用了一个助手:

module ApplicationHelper

  def users_roles user
    roles = ''
    user.roles.each do |role|
      roles << "#{role.name} "
    end
    roles
  end

end

那么你就可以把它放在你的视图中:

<td> <%= users_roles(current_user) %> </td>