簡體   English   中英

如何正確地從兩張表中收集信息,並在導軌中的一個控制器中使用它們?

[英]How do I properly gather information from two tables and use them in one controller in rails?

我有兩個表,分別名為usersbilling 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM