【发布时间】:2016-06-09 18:06:13
【问题描述】:
我想用 Microposts 建立一个供稿:
首先我用visible_for 'following'从我的追随者那里收集所有微博
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状态“联系人”)收集所有微博
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_feed 和contacts_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
【问题讨论】:
-
我认为代码的第一个sn-p有错字:las SQL查询中的
contact_ids_subselect应该是following_ids_subselect? -
什么是
.paginate方法?它可以应用于可枚举的对象吗? -
NickGnd 你是对的,我已经更正了。 Paginate 需要一个活动记录对象。例如不能应用数组(据我所知)
标签: ruby-on-rails activerecord ruby-on-rails-5