【问题标题】:Rails activity feed from a polymorphic following来自多态关注的 Rails 活动提要
【发布时间】:2014-03-07 20:48:45
【问题描述】:

我正在跟踪以下表格:

Story (id, user_id, content)
Vote  (id, user_id, story_id)
Flag  (id, user_id, story_id)
etc..

带有活动表:

Activity (id, user_id,action, trackable_id, trackable_type)

关系表:

Relationship (id, follower_id, followed_id)

我目前正在获取用户关注的用户的活动,如下所示:

def get_activity_from_followers(current_user)
     followed_user_ids = "SELECT followed_id FROM relationships
                         WHERE follower_id = :user_id"
    where("user_id IN (#{followed_user_ids})",
          user_id: user.id)
end

我的问题是,我如何获得可跟踪表(例如故事、投票、标志)属于您的活动。
所以现在我得到了类似的东西:

  1. “您正在关注的人”发布了一个故事
  2. “您关注的人”为故事投票


我还想得到类似的东西:

  1. “您未关注的人”为您的故事投票
  2. “您未关注的人”标记了您的故事

我该怎么做?谢谢。

【问题讨论】:

  • 你考虑过使用scopes吗?范围封装活动记录查询或查询的一部分。范围是可组合的,因此您可以在模型中包含一些 where 子句,在另一个模型中包含一些常用的连接,并根据需要将它们组合在一起。
  • 谢谢韦恩。这很有趣,在这种情况下我该如何使用它?
  • 这就是我想写的答案,如果我有时间的话。为了解决这个问题,我需要创建一个带有项目模拟的 rails 项目。我不知道什么时候有时间尝试一下;同时,我希望该评论对您或其他回答者有用。
  • 哦,我明白了。非常感谢韦恩 :)
  • 您能帮我一个忙并发布您的类定义,仅包含关系吗?我绝对可以提供帮助。

标签: ruby-on-rails postgresql activerecord ruby-on-rails-4


【解决方案1】:

我建议你有以下类定义和关联:

# 用户 类用户:可跟踪 结尾 # 标志(id,user_id,story_id) 类标志:可跟踪 结尾 # 带有活动表: # 活动(id、user_id、action、trackable_id、trackable_type) 类活动真 结尾 # 关系表: # 关系(id、follower_id、following_id) 类关系“用户” belongs_to :following, :class_name => "用户" 结尾

现在,让我们查找您关注的用户的活动:

# 列出我的关注者的活动 Activity.where(:user_id => current_user.followings)

列出我的活动

current_user.activities

【讨论】:

    【解决方案2】:

    为了解决这个问题,我会使用投票和标志 id 而不是用户 id 来搜索 Activity。像这样的:

    def get_votes(current_user)
     stories = current_user.stories
     votes = Votes.where(story_id: stories.map {|s| s.id})
     activity = Activity.where(action: 'vote', trackable_id: votes.map{|v| v.id})
    end
    

    我做了一些假设。首先,您可以调用user.stories,然后在活动模型中的“动作”可以是投票或标志,并且 trackable_id 与投票和标志 id 相关。如果这不正确,无论如何您都可以大致了解。

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      制作 Activity STI 类怎么样?

      class Story < ActiveRecord::Base
        belongs_to :user
      end
      
      class Activity < ActiveRecord::Base
        belongs_to :story
        belongs_to :user
      end
      
      class Vote < Activity
        def to_partial_path
          'users/vote'
        end
      end
      
      class Flag < Activity
        def to_partial_path
          'users/flag'
        end
      end
      

      您可以将所有用户操作存储在同一个表中并从那里获取:

      Activity.where(user_id: uid).all 
      

      并且您将获得所有用户操作的返回数组,每个操作都具有正确的类型,这允许您为不同类型的操作实现多态逻辑(至于我的示例中的部分路径,它允许您编写如下内容:

      render Activity.where(user_id: uid).all  
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多