0

newbie alert...

for example: i have table Role and table User role has_many users

in rails 4, can i show all roles with count of total_users in every single role with just 1 query to DB ? so, in every record from role there are 1 additional column called total_users, total_users is count from User where "users"."role_id" = "roles"."id"

I try it many times and its doesnt work, i've tried:

roles = Role.joins(:users).group("roles.id").count

and it is just return value of count. what I want is, the return value of query is both of all data in Role and also count of users in single query.

this is what i hope for result:

[#<Role id: 1, holding_company_id: 1, name: "admin", created_at: nil, updated_at: nil, description: nil, **total_users: ...** >, #<Role id: 2, holding_company_id: 2, name: "user", created_at: nil, updated_at: nil, description: nil, **total_users: ...**>]

anyone can help me for this very simple problem?? i used postgreSQL

1 Answer 1

0

You should keep those two results in separate variable.

roles = Role.joins(:users).group("roles.id")

roles_count = roles.count

Because roles contain, Array of table rows, and count has single value, we should keep it separately.

if you take both in single object it hard to process the values

Sign up to request clarification or add additional context in comments.

1 Comment

so in the end, there is no other way to combine total_users into Array of table of roles ??

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.