Rails5如何使用ActiveRecord Relation对象构建一个feed

时间:2016-06-09 18:06:14

标签: ruby-on-rails activerecord ruby-on-rails-5

我想用Microposts构建一个feed:

首先,我使用visible_for 'following'

收集我的所有Microposts
following_ids_subselect = "SELECT followed_id FROM relationships
                           WHERE  follower_id = :user_id"
following_feed = Micropost.where("visible_for = 'following' 
                                   AND user_id IN (#{following_ids_subselect})", user_id: id)

然后我使用visible_for 'contact'

从我的以下(AND状态“联系人”)收集所有Microposts
contacts_ids_subselect = "SELECT followed_id FROM relationships
                          WHERE  follower_id = :user_id
                          AND status = 'contact'"
contacts_feed = Micropost.where("visible_for = 'contacts' 
                                   AND user_id IN (#{contacts_ids_subselect})", user_id: id)

有没有办法让following_feedcontacts_feed在一起?我可以写:

@feed_items = global_feed.paginate(page: params[:page])

换句话说: global_feed应包含当前用户跟随visible_for 'followers'的用户的所有微博 + 使用status 'contact' }的visible_for 'contacts'跟随来自用户的所有微博

更新

关系

class Relationship < ApplicationRecord
# Table name: relationships
#
#  id           :integer(4)      not null, primary key
#  follower_id  :integer(4)
#  followed_id  :integer(4)
#  status       :string        

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

用户

class User < ApplicationRecord
  has_many :active_relationships, class_name:  "Relationship",
                              foreign_key: "follower_id",
                              dependent:   :destroy
  has_many :following, through: :active_relationships, source: :followed
  has_many :passive_relationships, class_name:  "Relationship",
                               foreign_key: "followed_id",
                               dependent:   :destroy
  has_many :followers, through: :passive_relationships, source: :follower
  (..)
end

微柱

class Micropost < ApplicationRecord
#
# Table name: microposts
#
#  id          :integer(4)      not null, primary key
#  user_id     :integer(4)
#  content     :string
#  visible_for :string   

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

1 个答案:

答案 0 :(得分:1)

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="Volume-Container"> <div class="value">0%</div> <div id="Volume-Bar"></div> </div>是仅在ActiveRecord关系上可用的方法。这意味着您需要在一个查询中选择所需的数据。

因此,如果我正确阅读您的示例,您希望当前用户的所有#paginate跟随Micropostcontacts可见的用户。

您可以在一个查询中选择它们

following