Skip to content

Instantly share code, notes, and snippets.

@rodloboz
Created April 26, 2019 15:19
Show Gist options
  • Save rodloboz/7dbfd11f083cb936276106259199daf3 to your computer and use it in GitHub Desktop.
Save rodloboz/7dbfd11f083cb936276106259199daf3 to your computer and use it in GitHub Desktop.
module Followable
extend ActiveSupport::Concern
included do
has_many :follower_relationships, foreign_key:
:following_id,
class_name: 'Follow'
has_many :followers, through: :follower_relationships, source: :follower
has_many :following_relationships, foreign_key:
:follower_id, class_name: 'Follow'
has_many :following, through: :following_relationships, source: :following
end
def follow(user_id)
following_relationships.create(following_id: user_id)
end
def unfollow(user_id)
following_relationships.find_by(following_id: user_id).destroy
end
def is_following?(user_id)
relationship = Follow.find_by(follower_id: id, following_id: user_id)
return true if relationship
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment