【问题标题】:view role titles of the user through assignment table通过分配表查看用户的角色头衔
【发布时间】:2011-01-18 01:30:17
【问题描述】:

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

我有一个榜样:
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 但它没有用

【问题讨论】:

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


    【解决方案1】:

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

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

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

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

    【讨论】:

      猜你喜欢
      • 2023-02-14
      • 1970-01-01
      • 2017-10-20
      • 2021-04-17
      • 1970-01-01
      • 2010-10-09
      • 2010-12-18
      • 2022-11-21
      • 2021-04-11
      相关资源
      最近更新 更多