【问题标题】:Rails views-table to display value from another modelRails 视图表以显示来自另一个模型的值
【发布时间】:2017-03-28 11:40:21
【问题描述】:

我的视图中有一个<table>,但它显示的是另一个模型的用户名 -Profile。我正在为表格的每一行调用 Profile。这样做有两个问题:通过调用它来暴露我的模型以及每次调用 Profile 这是低效的。

有没有办法先用一个 SQL 查询访问控制器中的所有用户名,然后相应地只显示表中的每个值,或者有更好的方法来显示没有表的值?

           <table class="table table-bordered table-striped">
            <thead>
            <tr>
              <th> Applicant Name </th>
              <th> Email </th>
              <th> Documents </th>
            </tr>
            </thead>
            <tbody>
              <% employee.eager_load(:application).each do |e_application| %>
                <tr>
                  <td><%= Profile.find_by_user_id(e_application.user_id).full_name %></td>
                  <td><%= mail_to(e_application.applicant.email) %></td>
                  <td><%= link_to e_application.doc.file.basename, e_application.doc_url if !eapplication.doc.file.nil? %></td>  
                </tr>
              <% end %>
            </tbody>
          </table>

非常感谢。我是 Rails 新手,没有找到任何示例。

【问题讨论】:

    标签: ruby-on-rails forms html-table views


    【解决方案1】:

    一开始就不要做

    Profile.find_by_user_id(e_application.user_id).full_name
    

    如果你的关系正确,只需调用

    e_application.user.full_name
    

    如果你并不总是有用户

    e_application.try(&:user).try(&:full_name)
    

    使用它,以免出错。

    单点符号总是好的,但对于这个例子来说,不需要复杂化。

    【讨论】:

    • 感谢塞达。但用户表没有全名,只有配置文件表有全名。要获取每个应用程序的用户名,e_application.user 将无济于事。我可以收集配置文件数组中的所有用户名然后映射吗?
    【解决方案2】:

    首先,将profile 表包含在员工列表中。

    例如。

    我假设

    员工

     belongs_to :user 
    

    用户

     has_one :profile
    

    那么,

    employee = Employee.includes(user: [:profile], :application).where(your condition)
    

    然后简单显示如下:

     <% employee.each do |e_application| %>
                    <tr>
                      <td><%= e_application.user.profile.full_name %></td>
    

    【讨论】:

    • 谢谢,Chakreshwar,但我没有遵循如何在用户中包含个人资料...员工是用户中的枚举角色。
    • 我不确定是否可以使用数组中的 where 查询或 e_application 控制器中的哈希以某种方式从配置文件中获取所有 full_name,并使用该数组/哈希将其映射到每个表行。当我显示时,我必须使用 user_id 作为键映射表行的哈希值。要显示的部分看起来很复杂,从哈希中获取。任何想法
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-15
    • 1970-01-01
    • 1970-01-01
    • 2015-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多