简体   繁体   English

Rails-计算外键记录

[英]Rails - count foreign key records

I have 2 tables - users and requests. 我有2个表-用户和请求。 The user table has many requests. 用户表有很多请求。 The requests records have user_id as a foreign key to the user table. 请求记录具有user_id作为用户表的外键。

When I display the index for users, I'd like to display the number of requests for each user. 当显示用户索引时,我想显示每个用户的请求数。

I'm sure this isn't close - but it might give you and idea of what I'm trying to do: 我确定这还没有结束-但这可能会给您和我正在尝试做的事情的想法:

<td><%= user.sign_in_count %></td>
<td><%= @worequests.where("user_id = user.id").count %></td>

Any ideas? 有任何想法吗?

I believe this should do it 我相信这应该做到

 user.requests.count

Basically go through the user model to count all the requests it owns. 基本上,通过用户模型来计算它拥有的所有请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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