ActsAsTaggableArrayOn
A simple implementation for tagging sysytem with postgres array.
Installation
Add this line to your application's Gemfile:
gem 'acts-as-taggable-array-on'
And then execute:
bundle
Setup
To use it, you need to have an array column to act as taggable.
class CreateUser < ActiveRecord::Migration
def change
create_table :users do |t|
t.text :tags, array: true, default: '{}'
t.
end
add_index :users, :tags, using: 'gin'
end
end
and bundle:
rake db:migrate
then
class User < ActiveRecord::Base
acts_as_taggable_array_on :tags
end
@user = User.new(:name => "Bobby")
acts_as_taggable_array_on defines 4 scope and 2 class methods as below.
scopes
- with_any_#tag_name
- with_all_#tag_name
- without_any_#tag_name
- without_all_#tag_name
class methods
- all_#tag_name
- #tag_name_cloud
Usage
Set, add and remove
#set
@user. = ["awesome", "slick"]
@user. = '{awesome,slick}'
#add
@user. += ["awesome"]
@user. += ["awesome", "slick"]
#remove
@user. -= ["awesome"]
@user. -= ["awesome", "slick"]
Finding Tagged Objects
class User < ActiveRecord::Base
acts_as_taggable_array_on :tags
scope :by_join_date, ->{order("created_at DESC")}
end
# Find a user with all of the tags
User.("awesome")
# Find a user with any of the tags
User.("awesome")
# Find a user without all of the tags
User.("awesome")
# Find a user without any of the tags
User.("awesome")
# Chain with the other scopes
User.("awesome").("slick").by_join_date.paginate(:page => params[:page], :per_page => 20)
Tag cloud calculations
Calculation to count for each tags is supported. Currently, it does not care its order.
User.
# [['awesome' => 1], ['slick' => 2]]
All Tags
Can get all tags easily.
User.
# ['awesome', 'slick']
Contributing
- Fork it ( http://github.com/
/acts-as-taggable-array-on/fork ) - Create your feature branch (
git checkout -b my-new-feature) - Commit your changes (
git commit -am 'Add some feature') - Push to the branch (
git push origin my-new-feature) - Create new Pull Request