通过分配表查看用户的角色标题

时间:2011-01-18 01:30:17

标签: ruby-on-rails ruby-on-rails-3 activerecord devise

嘿,我希望你能在这里帮助我。

我有一个角色模型:
has_many :users, :through => :role_assignments
has_many :role_assignments

角色分配模型:
belongs_to :user
belongs_to :role

和用户模型:
has_many :roles, :through => :role_assignments
has_many :role_assignments

我想在视图中显示用户角色。 我试过像user.roles.names这样的东西,但它没有用

1 个答案:

答案 0 :(得分:2)

由于user.roles是角色的集合(数组),因此无法直接调用名称。现在我假设您要访问的属性是名称,因此在这种情况下您可以执行:

user.roles.map(&:name).join(", ")

将收集角色中的所有名称,然后将它们加入由逗号分隔的字符串中。这很简单,也不是很灵活。如果你想以某种方式设计它,你可以这样做:

<% user.roles.each do |role| %>
  <p>Role: <%= role.name %></p>
<% end %>