设计和翻译 - 显示所有用户 - 角色 - 多个角色

时间:2015-05-20 11:48:10

标签: devise roles rolify

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

    <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>

管理员控制器:

    <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 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

2 个答案:

答案 0 :(得分:3)

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

视图/用户/ 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>

答案 1 :(得分:0)

我使用了一个帮手:

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>