My migration looks like this:
create table :posts do |t|
t.string :tags, array: true, default: []
end
How can I get an array of all the unique tags stored under tags in all posts?
You can do it inside the database with:
select distinct unnest(tags) from posts
So if you just want the strings then you can go straight to the database with:
tags = Post.connection.select_rows('select distinct unnest(tags) from posts').flatten
If there is a lot overlap amongst the tags arrays or a lot of arrays then that should be faster then pulling all the arrays out of the database and doing the data wrangling in Ruby.
Post.select('DISTINCT unnest(tags) AS uniq_tags').pluck(:uniq_tags).flatten -- select_rows seems like a bit of a hackish way of getting at it.Post class method anyway. I don't think you'd need that flatten call, you need it with select_rows because it returns an AoA even if each row in the result set has only one entry.I believe you could also do this:
Post.pluck(:tags).flatten.uniq
If you have a ton of posts this may be a fairly significant hit on performance though...
Post.pluck(:tags).uniq would return all the unique tag-sets. This is the down-side to using an array column instead of a many-to-many tag association table.