Group By Array in PostgreSQL

  • Jun 26

Previously we showed that you can implement tags with PostgreSQL array type. What if you want to count how many topics belong to a given tag ? You can still use the combination of group and count.

current_user.ownerships.group("unnest(ownerships.tags)").count

It will gives you a hash like this:

{"work"=>6, "family"=>1, "meeting"=>1, "2015"=>1}