我知道标题有点混乱,但是我的问题很简单。我在Rails 5应用程序中拥有两个模型。用户和费用。每个费用都属于一个用户。我有一个索引页面,其中列出了所有费用。我可以从费用表中列出每个费用的用户ID,但我想改为在用户表中查找用户名(在用户名列中),并与费用一起显示。我写的视图如下。但这是行不通的。
<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>
好的,所以在您的迭代中,@expenses
您具有以下这一行:
<%= User.joins(:expense).where('expense.user_id = ?', @user.id) %>
您可以将其更改为:
<% user = expense.user %>
请注意,我使用的<%
不是,<%=
因为我只是试图分配一个变量,而不是将输出打印到html。
然后在定义之后user
就可以说了<%= user.name %>
。
您应该阅读有关活动记录关联的更多信息,但这是有关所显示查询的一些补充说明
User.joins(:expense).where('expense.user_id = ?', @user.id)
在这种情况下,您应该使用生成的方法,belongs_to
而不要编写查询。但是在确实要编写自定义查询的情况下,只应where
在要获取数组时使用。在这种情况下,您正在寻找一条记录,因此可以使用find_by
。此外,您在此处执行的联接也是不必要的
# 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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句