Parry Parry - 1 year ago 40
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>


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

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

Answer Source

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

<%= User.joins(:expense).where('expense.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 <%= %>.

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 = ?',

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)