[英]How to combine two scopes with OR
我有一個標簽提要和一個朋友提要。 我想將這兩者結合起來並構建最終的“全部”提要。
對於朋友飼料:
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
對於標簽提要:
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
我會從控制器調用類似的東西(我使用 Kaminari gem 進行分頁):
@tag_feed = Post.tagfeed(current_user).page(params[:page]).per(21)
@friend_feed = Post.friendfeed(current_user).page(params[:page]).per(21)
現在我想要一個通用的飼料,但我迷路了。 范圍旨在縮小范圍,但在這種情況下,我正在嘗試進行 OR 操作。 做類似的事情
@mother_of_all_feed = @tag_feed + @friend_feed
將是多余的,我將無法控制出現在單個頁面上的帖子數量。 我該怎么做呢? 謝謝!
順便說一下,對於標簽,我的關聯設置如下:
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
此功能有一個 rails 拉取請求( https://github.com/rails/rails/pull/9052 ),但與此同時,有人創建了一個猴子補丁,您可以將其包含在您的初始值設定項中,這將允許您或范圍和一個查詢中的 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)}
回答我自己的問題。 我想我想出了一個辦法。
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.*")
)
到目前為止似乎工作正常,希望就是這樣!
這是我如何組合兩個范圍的示例。
scope :reconcilable, -> do
scopes = [
with_matching_insurance_payment_total,
with_zero_insurance_payments_and_zero_amount
]
where('id in (?)', scopes.flatten.map(&:id))
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.