Ruby on Rails – Using Tags as Model field

If you have a separate model for a Tag and manage them separately, it is pretty easy to attach those tags to another model via a field “tags_ids”. But, let’s say, you’ve got some SEO-settings for a object. It wouldn’t make much sense to store tags in a separate model for all your other pages.

To store tags as a property of any given object we will utilise PostgreSQL’s ability to have an array as data type. So, first of all, I don’t want to add all SEO-fields to every other object over and over again. Let’s create a separate SEO-model:

Then add the keyword column:

Add references to appropriate other tables:

For front-end editing I’m using bootstrap-tagsinput (here is an example). Install it via yarn add bootstrap-tagsinput(or download files manually). Don’t forget to include JS aswell as CSS files.

On the front-end part it is important to use a select field instead of simple text_field to be able to select multiple tags. Here is my full html code for the seo block:

For the backend part include seo to your corresponding models:

In your controller, whitelist the attributes (important to use keywords: [] to indicate an array) and don’t forget to build┬áthe fields if they aren’t present yet.

Now you can enjoy setting any variable tags and them being persistent in your database. Happy coding!

 

Published by

Anton

Hello! My name is Anton. I am a passionate project manager who loves digging deep into code. You can check my Github and CodeEval. Hopefully my thoughts on management can lead you to one or another good idea.