[Solved] How do I stop circular “followers” in a model?


You could write a custom validator function:

For example(assumption, you have a followed_users method which returns all the users that the current user is following, and a follow method, taking a user id and “following this user.):

class User < ActiveRecord::Base

    has_many :users, inverse_of :user, as: followed_users
    validates :verify_no_circular_followers

    def followed
       followed_users
    end

   def follow(user_id)
      followed_users << User.find(user_id)
   end

   private
      def verify_no_circular_followers
          followed_users.each do |u|
             if u.index(self)
                return false
             end
          end
          return true
      end
end

3

solved How do I stop circular “followers” in a model?