ruby on rails - How do I stop circular "followers" in a model? -
basically, have table 2 columns, follower , followed. if user1 follows user2, need make sure user2 cannot follow user1. write in model validate that?
i have user model each 1 has id. created new relationship model, there 2 columns.
this i'm at.
class relationship < activerecord::base attr_accessible :followed_id, :follower_id belongs_to :followed, class_name: "user" belongs_to :follower, class_name: "user" validates :followed_id, presence: true validates :follower_id, presence: true validates :verify_no_circular_requirements private def verify_no_circular_requirements return true end end
you write custom validator function:
for example(assumption, have followed_users method returns users current user following, , follow method, taking user id , "following 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 |u| if u.index(self) return false end end return true end end
Comments
Post a Comment