在 Rails 中正确呈现角色描述

Render the Role description correctly in Rails

我是 rails 的新手,我有用户。每个用户都通过 role_id 获得了一个角色。这些角色具有 admin, customer 等描述。我想在用户详细信息页面列表中显示角色。

我的代码如下所示:

<%= gravatar_for user, size: 70 %>
<p3>
  <%= user.firstname %> <%= user.name %><br>
</p3>
<p4>
  <%=user.email %><br>
  Role:<br>xxxxxx
</p4>

我必须为 xxxxxx 写什么才能显示 role description

如果你想发挥作用,那么方法如下

更新一: 如果用户 table 有一个角色

Role: <br> <%= user.role.try(:description) %>

更新 2: 如果用户 table 有多个角色

Role: <br> <%= user.roles.pluck(:description).join(",") %>

我正在考虑以下关系:

class User
  has_one :role
end

class Role
  belongs_to :user
end

角色 table 包含 id, description 等属性。
因此,要显示 description(admin, customer,user, etc) ,请使用以下内容:

Role: <br> <%= user.role.description %>