简体   繁体   中英

How to count the object number instead of getting all object in Ruby?

For Example, I want to know the User have how many post. So, I do it in this way;

user.posts.length

It works, but when I see the server log, it shows me that:

SELECT * FROM "posts" WHERE ("posts".user_id = 6) 

actually, I need to know the post number only, how can I do this? Thank you.

user.posts.count

# This will generate this:
SELECT count(*) AS count_all FROM `posts` WHERE (`posts`.user_id = 1) 

尝试这个:

 user.posts.count

You can use count/size method instead of length:

user.posts.count

It will execute query similar to:

SELECT COUNT(*) AS count_id FROM "posts" WHERE ("posts".user_id = 6) 

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