Monster on Fire

Configuring act_as_taggable_on gem to use commas with Rails 4.2.5

10 December 2016

Last week I worked on an issue where I had to add category tags to a particular model in our backend. While attempting a manual implementation, I found there was a gem that did this.

Problem

When it came to configuring the delimiter characters, the README on the repository wasn't very clear.

With the default implementation of the gem, the behaviour is as follows:

  • Add tags in input field and save
  • When you attempt to edit tags, all commas used to separate the tags have been stripped

This behaviour is apparently by design.

Goal

Configure acts_as_taggable_on to use both spaces and commas to separate tags. And make sure commas are not stripped when editing.

Installation

Following the gem's README:

# Gemfile
gem 'acts-as-taggable-on'

and in the terminal, bundle:

bundle install

run migrations

rake acts_as_taggable_on_engine:install:migrations
rake db:migrate
Model integration
#app/models/trip.rb
class Trip
  acts_as_taggable
end
Controller integration

Add :tag_list to the whitelist

#app/controllers/trips_controller.rb
def create
  @trip = Trip.create(trip_params)
  redirect_to @trip
end

private

def trip_params
  params.require(:trip).permit(:tag_list)
end
Add resource to routes
# config/routes.rb
resources :tags, only:[:index, :show]
Configuring delimiters

Add the delimiters to the Application_controller

#app/controllers/application_controller.rb
ActsAsTaggableOn.delimiter=[',',' ']

Then in the form, the syntax for the input should be:

#app/views/trips/_form.html.haml
= f.input :tag_list, label: "Tags", input_html: { value: @trip.tag_list.to_s }
Views
#app/views/trips/show.html.slim
h2 Tags
= render @trip.tags
Helpful Links:

That is all.

© 2020 - monsteronfire.com