0

I have setup a following follower relationship just as mentioned in Michael Hartl's Rail Tutorial. And I am using getstream to generate notifications whenever a user gets followed

class Relationship < ApplicationRecord
  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"
  validates :follower_id, presence: true
  validates :followed_id, presence: true

  default_scope { order(created_at: :desc) }

  include StreamRails::Activity
  as_activity

  def activity_actor
    self.follower
  end

  def activity_object
    self
  end

  def activity_verb
    "follow"
  end

  def activity_target
    self.followed
  end

  def activity_notify
    [StreamRails.feed_manager.get_notification_feed(self.followed.id)]
  end
end

And this is the User class:

class User < ApplicationRecord
  has_many :active_relationships,  class_name:  "Relationship",
                                   foreign_key: "follower_id",
                                   dependent:   :destroy
  has_many :passive_relationships, class_name:  "Relationship",
                                   foreign_key: "followed_id",
                                   dependent:   :destroy
  has_many :following, through: :active_relationships,  source: :followed
  has_many :followers, through: :passive_relationships, source: :follower
end

When I try to destroy a user, it destroys the associated relationships as well, because of dependent destroy. But stream rails throws following error in destroying the notification activities for relationship

Something went wrong deleting an activity: undefined method `id' for nil:NilClass
NoMethodError: undefined method `id' for nil:NilClass
from /home/yogen/.rvm/gems/ruby-2.4.4@stormy-island/gems/stream_rails-2.5.2/lib/stream_rails/activity.rb:34:in `activity_owner_id'

It works for other dependent destroy associations, but only fails for this one. Anyone know why?

1 Answers1

0

Alright, makes sense, because the User object is destroyed first, dereferenced from the Relationship's follow attribute, and then the Relationship is being destroyed without a follow attribute.

One way to solve this is to destroy all follow Relationships yourself, before destroying the User.

Another way is to NOT destroy the activity in the notification feed. To do that you can override the SyncDestroy policy (https://github.com/GetStream/stream-rails/blob/master/lib/stream_rails/sync_policies.rb#L29) for the Relationship model.

If both options are not good enough for you, you can still get rid of the SyncDestroy policy and implement your own. For example: add a custom policy on the User model that uses the feed_manager to destroy all activities for all the linked Relationship models.

Cheers

hannesvdvreken
  • 4,858
  • 1
  • 15
  • 17