0.0
Low commit activity in last 3 years
A lightweight Rails Engine that enables any ActiveRecord model to associate with predefined badges via polymorphic many-to-many relationships. Features database-level constraints, namespace isolation, and optional short aliases.
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
 Dependencies

Runtime

>= 6.0, < 9.0
 Project Readme

rails_badgeable

A lightweight, reusable Rails Engine for adding badges to any ActiveRecord model via polymorphic many-to-many relationships.

Installation

Add this line to your application's Gemfile:

gem 'rails_badgeable'

Then run:

rails rails_badgeable:install:migrations
rails db:migrate

Usage

Include the concern in any model:

class Post < ApplicationRecord
  include RailsBadgeable::HasBadges
end

post = Post.create(title: "Hello")
# Create or find a badge named "Important"
badge = RailsBadgeable::Badge.find_or_create_by(name: "Important")

# Assign the badge to post
post.badges << badge

# Query: Which posts have this badge assigned?
# Returns all Post records with the "Important" badge
# !!! Note, badge.posts syntax is not supported.
badge.assigned_to(Post)  # => [post]

# Query: Which badges have been used on the Post model?
# Returns all badges that have ever been assigned to a Post (excluding unused ones)
RailsBadgeable::Badge.for_model(Post)  # => [badge]

Using Short Alias (Optional)

If you prefer using Badge instead of RailsBadgeable::Badge, use the generator to create an alias initializer:

rails generate rails_badgeable:alias

This creates config/initializers/badgeable.rb with the following:

Badge = RailsBadgeable::Badge unless defined?(Badge)
BadgeAssignment = RailsBadgeable::BadgeAssignment unless defined?(BadgeAssignment)

Then you can use the short form:

# Instead of RailsBadgeable::Badge
Badge.find_or_create_by(name: "Important")

# Instead of RailsBadgeable::BadgeAssignment
BadgeAssignment.all

Available Methods

Instance Methods (on a Badge object)

  • badge.assigned_to(klass) - Returns all records of the given class that have this badge

Class Methods (on Badge class)

  • RailsBadgeable::Badge.for_model(klass) - Returns all badges ever used on the given model class

Model Methods (on models with HasBadges)

  • post.badges - Returns all badges assigned to this post
  • post.badges << badge - Assign a badge to this post
  • post.badges.destroy(badge) - Remove a badge from this post