Ask A Question

Notifications

You’re not receiving notifications from this thread.

Whats the best way to handle subscriptions with a forum?

Stephen Sizer asked in Rails
I'm building a forum and was wondering what's the best way to handle subscriptions? 
Reply
Hey Stephen,

So what I did was mimicked Github's Notifications section on Issues. You can see it on the forum here at the bottom of the right sidebar.

Here's what my model looks like. Basically, this tracks who opts in and who opts out. Then we can send the notifications accordingly. 

```ruby
# == Schema Information
#
# Table name: forum_subscriptions
#
#  id                :integer          not null, primary key
#  forum_thread_id   :integer
#  user_id           :integer
#  subscription_type :string
#  created_at        :datetime         not null
#  updated_at        :datetime         not null
#
# Indexes
#
#  index_forum_subscriptions_on_forum_thread_id  (forum_thread_id)
#  index_forum_subscriptions_on_user_id          (user_id)
#

class ForumSubscription < ApplicationRecord
  belongs_to :forum_thread
  belongs_to :user

  scope :optin, ->{ where(subscription_type: :optin) }
  scope :optout, ->{ where(subscription_type: :optout) }

  validates :subscription_type, presence: true, inclusion: { in: %w{ optin optout } }
  validates :user_id, uniqueness: { scope: :forum_thread_id }

  def toggle!
    case subscription_type
    when "optin"
      update(subscription_type: "optout")
    when "optout"
      update(subscription_type: "optin")
    end
  end
end
```

When sending notifications you'll want to build up the list of users like so:

1. All the users who posted in the thread
2. Add all the users who opted in to receive notifications for the thread
3. Remove all the users who opted out
4. Profit???
Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.