Skip to content

Instantly share code, notes, and snippets.

@kivanio
Forked from uguisu-an/followable.rb
Created June 22, 2014 21:49
Show Gist options
  • Save kivanio/ca51170e1c67716fd859 to your computer and use it in GitHub Desktop.
Save kivanio/ca51170e1c67716fd859 to your computer and use it in GitHub Desktop.
# app/models/concerns/followable.rb
module Followable
extend ActiveSupport::Concern
included do
has_many :reverse_relationships, :class_name => 'Relationship',
:as => :following,
:dependent => :destroy
has_many :followers, :through => :reverse_relationships,
:source => :follower
end
end
# app/models/concerns/following.rb
module Following
extend ActiveSupport::Concern
included do
has_many :relationships, :foreign_key => 'follower_id',
:dependent => :destroy
end
def follow!(followable)
followable.followers << self
end
def unfollow!(followable)
relationship = relationships.find_by(following_id: followable.id,
followed_type: followable.class.name)
relationship.destroy!
end
def followed?(followable)
relationships.find_by(following_id: followable.id,
followed_type: followable.class.name)
end
end
# app/models/relationship.rb
class Relationship < ActiveRecord::Base
belongs_to :follower, :class_name => 'User'
belongs_to :following, :polymorphic => true
validates_presence_of :follower, :following
end
# app/models/user.rb
class User < ActiveRecord::Base
include Following
include Followable
has_many :followed_users, :through => :relationships,
:source => :following,
:source_type => 'User'
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment