使用 Public Activity 显示被关注的人

Using Public Activity to Show who has been followed

我正在使用 public activity 为关注的人的活动提供通知。我想以

的格式显示用户是否关注另一个用户
John Doe followed Sam Smith

但到目前为止我能做到的只是

John Doe followed 1

这是我的代码。关系控制者

class RelationshipsController < ApplicationController
 before_action :authenticate_user!

 def create
  @user = User.find(params[:followed_id])
  current_user.follow(@user)
  respond_to do |format|
    format.html { redirect_to @user }
    format.js
  end
 end

 def destroy
  @user = Relationship.find(params[:id]).followed
  current_user.unfollow(@user)
  respond_to do |format|
   format.html { redirect_to @user }
   format.js
  end
 end
end

关系模型

class Relationship < ApplicationRecord
 include PublicActivity::Model
  tracked owner: ->(controller, model) { controller && controller.current_user }

  belongs_to :follower, class_name: "User"
  belongs_to :followed, class_name: "User"

  validates :follower_id, presence: true
  validates :followed_id, presence: true
end

关系在 public_activity 文件夹中创建文件

<% if activity.trackable %>
  Followed <%= activity.trackable.followed_id %>
<% else %>
  Unfollowed a User
 <% end %>

您可能不想只渲染 followed_id,而是渲染 followed.name。变化:

Followed <%= activity.trackable.followed_id %>

像这样(将 name 替换为在您的应用程序中有意义的方法):

Followed <%= activity.trackable.followed.name %>