Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

has_many count column #1370

Closed
glennfu opened this issue Oct 24, 2012 · 2 comments
Closed

has_many count column #1370

glennfu opened this issue Oct 24, 2012 · 2 comments

Comments

@glennfu
Copy link

glennfu commented Oct 24, 2012

I have a User, which has_many :posts. I'd love to have a column that showed the # of posts, so I could sort my Users by the ones with the most posts. Is this possible?

@glennfu
Copy link
Author

glennfu commented Oct 24, 2012

I can do this manually, with Postgres support, by running:

    @users = User.select("(select COUNT(posts.id) from posts where posts.user_id = users.id) 
        AS posts_count, users.#{User.column_names.join(",users.")}").
        order("posts_count DESC").limit(30)

@bbenezech
Copy link
Collaborator

I would use a counter cache column to do that. Please use the mailing-list for assistance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants