Garbar
8/21/2016 - 9:29 AM

Polymorphic following, that has no dependencies on objects, that are followed

Polymorphic following, that has no dependencies on objects, that are followed

followable_concern.rb

module FollowableConcern
  extend ActiveSupport::Concern

  included do
    has_many :personal_followers, class_name: 'Core::Follow', as: :followingable, dependent: :destroy
    has_many :personal_followings, class_name: 'Core::Follow', as: :followerable, dependent: :destroy

    def followers
      personal_followers.map(&:followerable)
    end

    def followings
      personal_followings.map(&:followingable)
    end

    def follows?(person)
      personal_followings.find_by(followingable: person).present?
    end
  end
end

follow.rb

class Follow < ActiveRecord::Base
  belongs_to :followingable, polymorphic: true
  belongs_to :followerable, polymorphic: true
end

##How I use it

user.rb

class User < ActiveRecord::Base
  include FollowableConcern
  # some code here . . .
end

follows_controller

class FollowsController < ApplicationController
  before_action :set_person
  
  def create
    @following = current_user.personal_followings.create(followingable: @person)
    # some response here . . .
  end
  
  def destroy
    @following = current_user.personal_followings.find_by(followingable: @person)
    @following.destroy
    # some response here . . .
  end
  
  private 
  
  def set_person
    @person = params[:person_entity].from_entity
  end
end