-
-
Save kivanio/ca51170e1c67716fd859 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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