Means
Means

Reputation: 432

Rails views-table to display value from another model

I have a <table> in a view but it's showing username from another model -Profile. I'm calling Profile for each row of table. There are two problems with this: exposing my model in view by calling it & each time calling Profile which is inefficient.

Is there a way to access all usernames in controller first with one SQL query and then display only each value in table correspondingly or a better approach to show values without table?

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

Many thanks. I'm new to rails and not found any example.

Upvotes: 0

Views: 880

Answers (2)

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

First of all, include the profile table in the employee list.

For eg.

I am assuming that

employee

 belongs_to :user 

user

 has_one :profile

then,

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

then simply display as below:

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

Upvotes: 0

Sedad Kosovac
Sedad Kosovac

Reputation: 668

For start don`t do

Profile.find_by_user_id(e_application.user_id).full_name

If you did relations correctly just call

e_application.user.full_name

In case you don`t always have user

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

use this so you don`t get error.

Single dot notations is always good but for this example no need to complicate things.

Upvotes: 1

Related Questions