26

I have a tag feed and a friend feed. I want to combine these two and build the ultimate "all" feed.

For friend feed:

class Post < ActiveRecord::Base
  scope :friendfeed, lambda{|x| followed_by}

  def self.followed_by(user)
    where("user_id IN (?) OR user_id = ?", user.watched_ids, user.id)
  end
end

For tag feed:

class Post < ActiveRecord::Base
  scope :tagfeed, lambda{|x| infatuated_with}

  def self.infatuated_with(user)
    joins(:attachments).where("attachments.tag_id IN (?)", user.tags).select("DISTINCT pages.*")
  end
end

And I would call something like this from the controller (I'm using Kaminari gem for pagination):

@tag_feed = Post.tagfeed(current_user).page(params[:page]).per(21)
@friend_feed = Post.friendfeed(current_user).page(params[:page]).per(21)

Now I want to have a universal feed, but I'm lost. Scopes are meant for narrowing down, but in this case I'm trying to do an OR operation. Doing stuff like

@mother_of_all_feed = @tag_feed + @friend_feed

would be redundant, and I wouldn't be able to control the number of posts appearing on a single page. How can I go about doing this? Thanks!

By the way, for tags I have association set up like this:

class Post < ActiveRecord::Base
  has_many :attachments
  has_many :tags, :through => :attachments
end

class Tag < ActiveRecord::Base
  has_many :attachments
  has_many :posts, :through => :attachments
end

class Attachment < ActiveRecord::Base
  belongs_to :tag
  belongs_to :post
end
4

3 回答 3

17

此功能有一个 Rails 拉取请求(https://github.com/rails/rails/pull/9052),但与此同时,有人创建了一个猴子补丁,您可以将其包含在您的初始化程序中,这将允许您or 范围和 where 一个查询中的子句,仍然给你一个ActiveRecord::Relation

https://gist.github.com/j-mcnally/250eaaceef234dd8971b

有了它,您就可以像这样对您的范围进行 OR

Post.tagfeed(current_user).or.friendfeed(current_user)

或写一个新的范围

scope :mother_of_all_feed, lambda{|user| tagfeed(user).or.friendfeed(user)}
于 2013-05-15T18:40:22.503 回答
4

回答我自己的问题。我想我想出了一个办法。

where("pages.id IN (?) OR pages.id IN (?)",
  Page.where(
      "user_id IN (?) OR user_id = ?",
      user.watched_ids, user.id
  ),
  Page
    .joins(:attachments)
    .where("attachments.tag_id IN (?)", user.tags)
    .select("DISTINCT pages.*")
)

到目前为止它似乎正在工作,希望就是这样!

于 2012-05-24T10:14:01.623 回答
2

这是我如何组合两个范围的示例。

scope :reconcilable, -> do
  scopes = [
    with_matching_insurance_payment_total,
    with_zero_insurance_payments_and_zero_amount
  ]

  where('id in (?)', scopes.flatten.map(&:id))
end
于 2020-02-15T00:12:50.290 回答