Skip to content
Pat Allan edited this page Jul 10, 2021 · 2 revisions

Example

This example goes through adding Gutentag to a Rails application, and then adding in the appropriate form details to allow tags to be saved against an object.

Installing

First up, add Gutentag to your Gemfile:

gem "gutentag", "~> 2.1.0"

Then update your bundle:

bundle install

And now you can add in Gutentag's migrations and update your database:

bundle exec rake gutentag:install:migrations
bundle exec rails generate gutentag:migration_versions
bundle exec rake db:migrate

Adding to a model

In this example, we're adding tags to a Product model. So, in app/models/product.rb, we'd set up the tagging:

# near the top of your model, with other associations
Gutentag::ActiveRecord.call self

This means that Product instances now have many tags, and also have a tag_names accessor as a shortcut for setting/getting tag values. We're going to use that accessor (which returns an array) to build our own combined string value - combining the names with a space and comma, and the equivalent setter:

# This also goes in your model.

# Return the tag names separated by a comma and space
def tags_as_string
  tag_names.join(", ")
end

# Split up the provided value by commas and (optional) spaces.
def tags_as_string=(string)
  self.tag_names = string.split(/,\s*/)
end

Adding to a form view

Now that we have our tags as a single value, it's particularly easy to have it displayed and updated in a form. We can add it to the form view like so:

<!-- This would be the approach for a scaffold-generated model.
     Please adapt for your own view/form approach! -->
<div class="field">
  <%= form.label :tags_as_string, value: "Tags" %>
  <%= form.text_field :tags_as_string, id: :product_tags_as_string %>
</div>

And then in the controller, make sure that field is included in the permitted parameters:

# In my model, I already have a column 'name'. You may have others!
def product_params
  params.require(:product).permit(:name, :tags_as_string)
end

With all of this done, this model can now have tags set and changed. Of course, this example is taking a very simple approach - you may want a fancier interface than a text field, or perhaps want to manage tags more directly via the tags association.

Clone this wiki locally