Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add tagging with autocomplete to an existing model in Rails?

I'm trying to add "tags" to an Article model in a Rails 3 application.

I'm wondering if there is a gem or plugin that has adds both the "tagging" functionality in the model and also the auto-complete helpers for the views.

I've found acts_as_taggable but I'm not sure if that's what I should be using. Is there something newer? I'm getting results from 2007 when I google acts_as_taggable

like image 928
deb Avatar asked Feb 08 '11 19:02

deb


1 Answers

acts_as_taggable_on and rails3-jquery-autocomplete work nicely together to make a SO like tagging system see example below. I don't think a suitable all in one option exists yet for rails.

Follow these steps to get this all installed:

1 . Backup your rails app!

2 . Install jquery-rails

Note: You can install jQuery UI with jquery-rails but I chose not to.

3 . Download and install jQuery UI

Choose a theme that will compliment your web design (be sure to test the autocomplete demo with the theme you choose, the default theme did not work for me). Download the custom zip and place the [zipfile]/js/jquery-ui-#.#.#.custom.min.js file into your app's /public/javascripts/ folder. place the [zipfile]/css/custom-theme/ folder and all files into your app's public/stylesheets/custom-theme/ folder.

4 . Add the following to your Gemfile and then run "bundle install"

gem 'acts-as-taggable-on'
gem 'rails3-jquery-autocomplete'

5 . From the console run the following commands:

rails generate acts_as_taggable_on:migration
rake db:migrate
rails generate autocomplete:install

Make these changes in your app

Include the necessary javascript and css files in your application layout:

<%= stylesheet_link_tag "application", "custom-theme/jquery-ui-1.8.9.custom" %>   <%= javascript_include_tag :defaults, "jquery-ui-#.#.#.custom.min", "autocomplete-rails" %> 

Controller Example

EDIT: Made changes based on Seth Pellegrino's comments.

class ArticlesController < Admin::BaseController     #autocomplete :tag, :name  <- Old      autocomplete :tag, :name, :class_name => 'ActsAsTaggableOn::Tag' # <- New end 

Model Example

class Article < ActiveRecord::Base    acts_as_taggable_on :tags end 

Route.rb

resources :articles do   get :autocomplete_tag_name, :on => :collection     end 

View Example

<%= form_for(@article) do |f| %>   <%= f.autocomplete_field :tag_list, autocomplete_tag_name_articles_path, :"data-delimiter" => ', ' %>    # note tag_list above is a virtual column created by acts_as_taggable_on <% end %>  

Note: This example assumes that you are only tagging one model in your entire app and you are only using the default tag type :tags. Basically the code above will search all tags and not limit them to "Article" tags.

like image 85
Tim Santeford Avatar answered Sep 22 '22 05:09

Tim Santeford