ruby-on-rails - 来自多态追随者的 Rails 事件提要

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

我正在跟踪以下表格:

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. “您未关注的人”标记了您的故事

我该怎么做?谢谢。

最佳答案

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

# User 
class User  :trackable
end

# Flag  (id, user_id, story_id)
class Flag  :trackable
end

# with an activity table:
# Activity (id, user_id,action, trackable_id, trackable_type)
class Activity  true
end

# The relationship table:
# Relationship (id, follower_id, following_id)
class Relationship  "User"
  belongs_to :following, :class_name => "User"
end

现在,让我们查找您关注的用户的事件:


# List activities of my followings
Activity.where(:user_id => current_user.followings)

列出我的事件

current_user.activities

关于ruby-on-rails - 来自多态追随者的 Rails 事件提要,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22260385/

相关文章:

ruby-on-rails - Rails 的 concat 方法和带有 do...end 的 block 不起作用

ruby-on-rails - 通过 sprockets 在 Ruby on Rails 中的源映射

ruby-on-rails - Rails 3 中的嵌套属性

postgresql - 使用 lag 函数 postgres 的日期差异

postgresql - 如何在 PostgreSQL 中调整 SET intervalstyle(更改间隔输出)?

php - CodeIgniter 中的 ActiveRecord

ruby-on-rails - Rails 4 中的作用域数量

java - 为什么 myBatis+postgresql 9.3 即使查询成功也会发出 ROLLBACK ?

ruby-on-rails - Rails Activerecord 多个表包括

mysql - Controller 中的 Rails where 或子句