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

Already on GitHub? Sign in to your account

has_many count column #1370

glennfu opened this Issue Oct 24, 2012 · 2 comments


None yet
2 participants

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 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 commented Oct 25, 2012

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

@bbenezech bbenezech closed this Oct 25, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment