2017-03-28 113 views
0

我在视图中有一个<table>,但它显示来自另一个模型的用户名 - Profile。我为每个表格调用Profile。有两个问题:通过每次调用效率低下的配置文件调用&来暴露我的模型。Rails视图表显示来自另一个模型的值

是否有一种方法可以首先访问控制器中的所有用户名,并使用一个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> 

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

回答

1

对于启动不`吨做

Profile.find_by_user_id(e_application.user_id).full_name 

如果你没有关系正确就叫

e_application.user.full_name 

如果客人不愿意总有用户

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

使用该如此你没有得到错误。

单点符号总是很好,但在这个例子中,不需要使事情复杂化。

+0

谢谢Sedad。但用户表不具有full_name,只有配置文件表具有full_name。要获取每个应用程序的用户名,e_application.user将无能为力。我可以收集配置文件数组中的所有用户名,然后映射它吗? – Means

0

首先,在员工列表中包含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> 
+0

Thx,Chakreshwar,但我没有按照如何在用户中包含配置文件...员工是用户中的枚举角色。 – Means

+0

粘贴您的控制器代码和模型 –

+0

我不确定是否可以以某种方式使用数组中的where查询或e_application控制器中的散列获取所有full_name从配置文件中,并使用该数组/散列将其映射到每个表行。并且,当我显示时,我将不得不使用user_id作为关键字将该散列值映射到表行。要显示的部分看起来很复杂,以从哈希中获取。有任何想法吗 – Means

相关问题