简体   繁体   中英

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

I have two tables named users and billing . In users I have the usual information, while in billing (contains user_id field for reference) I have things like balances by month for each user. My problem comes from when I want to list the monthly balances. On the monthly balances page I want to display the user(s)'s name, balanace for the month and other misc information, however the billing table only holds the user's id.

At first i tried

@mondetail = Billings.find_by_date(201204) #April's billing period
@customer = Users.find_by_id(mondetail.user_id)

which works fine for one user but how should I go about this when I want to display the information from both tables with multiple users? Or would it just be best for me to add a user_name field to the billing table?

You don't need find user's info in controller. You can get it from Billing model. (Strange that models are plural)

# controller
@mondetail = Billings.includes(:user).find_by_date(201204)


# view
<% @mondetail.each |mondetail| %>
 <%= mondetail.user.name %><br />
 <%= number_to_currency mondetail.balance %>
<% end %>

It's will work and without includes but you should avoid N + 1 queries problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM