Most Rails app has some kind of need for tags. There’s plenty of gems out there and one of the most popular one is acts-as-taggable-on. But if you’re using PostgreSQL for your Rails app you can use PostgreSQLs array data type instead. In this blog post I’m going to show how you can make use of them in Rails 4.
Make sure you have the Rails 4 gem activated and PostgreSQL installed then run:
Next we need to update the migration file named create_documents:
Note that we have added the
array: true option to the tags attribute and that it defaults to an empty array.
Now you’re ready to create the database and run the migrations:
If you open up
psql, connects to your database and run
\d documents;, you should see that your tags column has
 at the end which means it will be treated as an array:
You can now open the Rails console and start playing with your document model:
As you can see, the tags property is now represented as an array. If you are curious about how it looks in PostgreSQL, use psql again:
To query your documents you can use the Active Record query API as you normally do:
It’s important to add an index for the tags column otherwise it’s going to be slow as hell. You have the option to choose between two types of indexes called GiST and GIN. Which one that will suit you depends on how you want to use the tags. Your can read more about the two index types in the PostgreSQL documentation: GiST and GIN Index Types
To add the index you can create this migration: