Reputation: 153
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
Upvotes: 0
Views: 93
Reputation: 3888
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
Upvotes: 0