Skip to main content

Whats the best way to handle subscriptions with a forum?

Rails • Asked by Stephen Sizer
295d228ecb9d1859d9ba2963f557a31c
I'm building a forum and was wondering what's the best way to handle subscriptions? 

Ce795239ba5dd2384fc2f88ffaff5451
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???

Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 18,000+ developers who get early access to new screencasts, articles, guides, updates, and more.

By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

More of a social being? We're also on Twitter and YouTube.