【问题标题】:Render the Role description correctly in Rails在 Rails 中正确呈现角色描述
【发布时间】:2017-07-20 16:37:58
【问题描述】:

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

【问题讨论】:

    标签: ruby-on-rails roles


    【解决方案1】:

    如果你想显示角色,那么下面是方法

    更新 1: 如果用户表只有一个角色

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

    更新 2: 如果用户表有很多角色

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

    【讨论】:

    • 我做了:Rolle:,当我这样做时,他显示了角色 ID (1,2,3,4....) 但没有描述:Rolle: 然后他说参数数量错误
    • @Feidex 你想显示role idsrole description
    • 我想显示角色描述。
    • 角色:
      作品谢谢 :)
    • @Feidex 欢迎 :)
    【解决方案2】:

    我正在考虑以下关系:

    class User
      has_one :role
    end
    
    class Role
      belongs_to :user
    end
    

    并且角色表包含​​id, description等属性。
    因此,要显示描述(管理员、客户、用户等),请使用以下内容:

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

    【讨论】:

    • 我是通过分配来做到这一点的:class Role
    • ok,表示一个用户有多个角色,所以可以显示第一个角色,比如 user.roles.first.description
    猜你喜欢
    • 2018-05-07
    • 2018-11-06
    • 2019-02-06
    • 1970-01-01
    • 2011-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多