![](/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.