Search code examples
ruby-on-railsdeviserolify

How to display role name associated with user using rolify gem?


I have tables Roles, Users and Users_Roles. Each user will have a role associated with it. How to display the role name associated with a user in view.

index.html:

<% @users.each do |user| %>
    <tr>
      <td><%= user.full_name %></td>
      <td><%= user.email %></td>
      <td class="text-center"><%= user.profile_name %></td>
      <td class="text-center"><%= user.client_list %></td></tr><% end %>

user.rb:

def profile_name
  Role.find(role_id).name
end

Solution

  • Add below method in model to get role of user

    user.rb

    def profile_name
     roles.collect(&:name).join(', ')
    end
    

    users_controller.rb

    def index
     @users = User.includes(:roles)
    end
    

    In view, call role method as user.profile_name.