Skip to content

Instantly share code, notes, and snippets.

@uguisu-an
Created May 23, 2014 23:00
Show Gist options
  • Save uguisu-an/22a0c38621e68a113dc1 to your computer and use it in GitHub Desktop.
Save uguisu-an/22a0c38621e68a113dc1 to your computer and use it in GitHub Desktop.
polymorphic N:N association + rails4 concerns
# 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