Skip to content

How to implement notifications for users on new badges

tute edited this page Apr 28, 2013 · 4 revisions

Active Record Observers are the tool for the job. You may add your notifications logic in a file named app/models/badges_sash_observer.rb. Follows a working example:

class BadgesSashObserver < ActiveRecord::Observer
  observe Merit::BadgesSash

  # A badge_sash has badge_id and sash_id foreign keys
  def after_create(badge_sash)
    # In this case the User model has a `has_merit` call,
    # and so has a sash_id foreign key
    user = User.find_by_sash_id(badge_sash.sash_id)

    MyAppMailer.badge_granted(badge_sash.badge_id, user.id).deliver

    # And whatever else your app uses for sending notifications!
  end
end