Skip to content

Instantly share code, notes, and snippets.

@mgreenly
Created January 21, 2012 19:18
Show Gist options
  • Select an option

  • Save mgreenly/1653646 to your computer and use it in GitHub Desktop.

Select an option

Save mgreenly/1653646 to your computer and use it in GitHub Desktop.
postgres aggregate string`
User.
select("users.id, users.full_name, string_agg(roles.name, ', ') as roles_col").
joins(:memberships => :role).
group('users.id').
each_with_object([[:id, :full_name, :roles]]){ |u,a|
a << [u.id, u.full_name, u.roles_col.split(',').map(&:strip) ]
}
SELECT
users.full_name,
string_agg(roles.name, ', ')
FROM
users
JOIN
memberships on memberships.user_id = users.id
JOIN
roles on roles.id = memberships.role_id;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment