A lightweight, reusable Rails Engine for adding badges to any ActiveRecord model via polymorphic many-to-many relationships.
Add this line to your application's Gemfile:
gem 'rails_badgeable'Then run:
rails rails_badgeable:install:migrations
rails db:migrateInclude 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]If you prefer using Badge instead of RailsBadgeable::Badge, use the generator to create an alias initializer:
rails generate rails_badgeable:aliasThis 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.allbadge.assigned_to(klass)- Returns all records of the given class that have this badge
RailsBadgeable::Badge.for_model(klass)- Returns all badges ever used on the given model class
post.badges- Returns all badges assigned to this postpost.badges << badge- Assign a badge to this postpost.badges.destroy(badge)- Remove a badge from this post