<img src=“https://secure.travis-ci.org/tscolari/categoryz3.png” /> <img src=“https://codeclimate.com/github/tscolari/categoryz3.png” />
__Version 0.9+ is rails4 compatible__
Simple categorization to ActiveRecord models.
Works like a simple tagging system, but instead of tags it has categories, and categories may have an ilimited level of subcategories.
Fetches items in any level of subcategories with a single join.
genres_category = Categoryz3::Category.create(name: 'genres') horror_category = Categoryz3::Category.create(name: 'horror', parent: genres_category) cult_horror_category = Categoryz3::Category.create(name: 'horror', parent: horror_category) action_category = Categoryz3::Category.create(name: 'horror', parent: genres_category) horror_movie = Movie.find(1) horror_movie.categories << cult_horror_category horror_movie.categories #=> [cult_horror_category] action_movie = Movie.find(2) action_movie.categories << action_category Movie.inside_category(genres_category).all #=> [horror_movie, action_movie] Movie.inside_category(horror_category).all #=> [horror_movie] Movie.inside_category(cult_horror_category).all #=> [horror_movie] horror_category.path #=> [movie_category, horror_category]
Insert the gem in your Gemfile:
gem 'categoryz3'
Generate and run the migrations:
rails g categoryz3:migrations rake db:migrate
Include the categorizable module in the models you want to categorize:
class Article < ActiveRecord::Base include Categoryz3::Categorizable end
You can use the relation ‘categories` to list all categories from a model:
model.categories #=> [category1, category2]
You can also use the ‘categories_list`, this will return the categories ids:
model.categories_list #=> "1, 2"
There are 2 ways for adding categories to an object:
model.categories << category model.categories_list = "1, 2, 3"
To remove a category from the model, you can use the ‘remove_category` method:
model.remove_category category model.remove_categories category1, category2
Lists all the categories in the path, from the root one, to the category:
category.path #=> [root_category, some_subcategory, another_subcategory, category]
Lists all objects that belongs to the category or any subcategory of it
Article.inside_category(category)
Lists all objects that belongs to the category. (No subcategory objects).
Article.having_category(category)
MIT License. Copyright 2012 Tiago Scolari.