![](/img/trans.png)
[英]How do i get values from a post form and use them in the rails controller
[英]How do I properly gather information from two tables and use them in one controller in rails?
我有兩個表,分別名為users
和billing
。 在users
我具有通常的信息,而在billing
(包含user_id
字段供參考),我具有諸如每個用戶按月的余額之類的東西。 我的問題出在我想列出每月余額時。 在每月余額頁面上,我想顯示用戶的姓名,月份的平衡符和其他其他信息,但是billing
表僅包含用戶的ID。
起初我嘗試過
@mondetail = Billings.find_by_date(201204) #April's billing period
@customer = Users.find_by_id(mondetail.user_id)
哪種方法對一個用戶來說效果很好,但是當我想同時顯示多個用戶的兩個表中的信息時,應該如何處理呢? 還是對我來說最好在billing
表中添加一個user_name
字段?
您不需要在控制器中查找用戶的信息。 您可以從Billing
模型中獲取。 (奇怪的是模型是復數的)
# controller
@mondetail = Billings.includes(:user).find_by_date(201204)
# view
<% @mondetail.each |mondetail| %>
<%= mondetail.user.name %><br />
<%= number_to_currency mondetail.balance %>
<% end %>
它可以工作並且沒有includes
但是您應該避免N + 1個查詢問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.