ruby-on-railspublic-activity

Tracking and displaying likes using public activity


I have been trying to figure out how to make it so that I can create an activity page that lists out likes by other users on your OWN individual posts. In my case, I have no friend or following system so literally anyone who signs up can like a post. I have been looking everywhere and cannot find an example of how it is done

Currently, I have defined a like method in my post controller

def like
  @post = Post.find(params[:id])
  @post.upvote_by current_user
  redirect_to :back
end

I also have an activities controller:

class ActivitiesController < ApplicationController
  def index
    @activities = PublicActivity::Activity.where(trackable_type: "Post", trackable_id: current_user.post_ids, key: "post.like")
  end
end

My Post model looks like this:

class Post < ActiveRecord::Base
  belongs_to :user
  acts_as_votable

  include PublicActivity::Model
  tracked only: [:create, :like], owner: Proc.new{ |controller, model| model.user }

  default_scope -> { order('created_at DESC') }
end

My activities view template looks like this:

<% @activities.each do |activity| %>
  <%= activity.inspect %>
<% end %>

As of right now, my notification page displays nothing. How do i go about displaying a feed showing all the likes that my posts received from other users. Thanks so much


Solution

  • When upvote_by is called on a post, an ActsAsVotable::Vote record is created. You therefore have to add public activity to this model if you want to log votes.

    class ActsAsVotable::Vote
      include PublicActivity::Model
      tracked only: [:create], owner: Proc.new{ |controller, model| model.user }
    end