Parry Parry - 1 month ago 4
Ruby Question

How to display value of a field from a different table by using the value of a different column in another table

I realize the heading is a little confusing but my problem is quite simple. I hae two models in my rails 5 app. User and Expense. Each expense belongs_to a user. I have an index page where all expenses are being listed. I can list the user IDs for each expense from the expenses table but I want to instead look up the name of the user (in column username) in the users table and display it with the expense instead. The view I have written is below. But it doesn't work.

<p id="notice"><%= notice %></p>

<h1>Teamjournals</h1>

<table style="padding: 2px; width: 50%" border="2px" align="center">
<thead>
<tr>
<td align="center"><%= link_to new_expense_path, :class =>"btn btn-success btn-wide" do%>Add New Expense<% end %></td>
</tr>
<tr>
<th>User</th>
<th>Expense Date</th>
<th>Currency</th>
<th>Expense Amount</th>
<th>Description</th>
<th colspan="1"></th>
</tr>
</thead>

<tbody>
<% @expenses.each do |expense| %>
<tr>
<td><%= User.joins(:expense).where('expense.user_id = ?', @user.id) %></td>
<td><%= expense.expense_date %></td>
<td><%= expense.currency.currency %></td>
<td align="right"><%= expense.expense %></td>
<td><%= expense.description %></td>
</tr>
<% end %>
</tbody>
</table>

Answer

Ok so in your iteration over @expenses you have this line:

<%= User.joins(:expense).where('expense.user_id = ?', @user.id) %>

you can change it to this:

<% user = expense.user %>

Note that I'm using <% not <%= because I'm just trying to assign a variable, not print the output to html.

Then after defining user you can say <%= user.name %>.

You should read a bit more about active record associations, but here's a few side comments about the query you've shown

User.joins(:expense).where('expense.user_id = ?', @user.id)

In this case, you should use the method generated by belongs_to instead of writing a query. But in situations where you do want to write a custom query, you should only be using where when you want to get an array. In this case you're looking for a single record so you could use find_by. Furthermore, the joins you're doing here is unnecessary

 # any of these works
 user = User.where('id = ?', expense.user_id).first
 user = User.where(id: expense.user_id).first
 user = user.find_by(id: expense.user_id)
Comments