使用 OR 组合多个命名范围 [英] Combining multiple named scopes with OR

查看:34
本文介绍了使用 OR 组合多个命名范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试合并两个范围或向现有范围添加更多范围.

scope :public_bids, ->{其中(状态:[状态::接受,状态::出价,状态::出售,状态::NO_SALE],bid_type: [BidType::MANUAL, BidType::AUTO, BidType::LIVE])范围:outbid_maxbids,->{其中(状态:状态:::出价,出价类型:出价类型::最大出价)

我无法确定如何将它们 OR 放在一起或合并到一个范围内.任何建议/指导?我更愿意将它们组合成一个单一的范围.

解决方案

我还没有尝试在作用域中使用 ,但是您可以使用 Rails 5 的新 <代码>或方法,像这样:

scope :public_or_outbid, ->{其中(状态:[状态::接受,状态::出价,状态::售出,状态::NO_SALE],出价类型:[BidType::MANUAL,BidType::AUTO,BidType::LIVE])\.or(where(status: Status::OUTBID, bid_type: BidType::MAXBID))}

(请注意,这只适用于 Rails 5)

您当然可以像这样将条件链接在一起:

MyObj.public_bids.or(MyObj.outbid_maxbids)

有关更多详细信息,请参阅此答案:Rails 5:ActiveRecord OR 查询

I am trying to combine two scopes or add some more to an existing scope.

scope :public_bids, -> {
  where(status: [Status::ACCEPTED, Status::OUTBID, Status::SOLD, Status::NO_SALE],
        bid_type: [BidType::MANUAL, BidType::AUTO, BidType::LIVE])
scope :outbid_maxbids, -> {
  where(status: Status::OUTBID, bid_type: BidType::MAXBID)

I am having trouble determining how to OR them together or combine then into one scope. Any suggestions/guidance? I would prefer that they be combined into one single scope.

解决方案

I haven't tried using or in a scope, but you may be able to chain the scopes together using Rails 5's new or method, like this:

scope :public_or_outbid, -> {
  where(status: [Status::ACCEPTED, Status::OUTBID, Status::SOLD, Status::NO_SALE], bid_type: [BidType::MANUAL, BidType::AUTO, BidType::LIVE])\
  .or(where(status: Status::OUTBID, bid_type: BidType::MAXBID))
}

(Note that this only works in Rails 5)

You certainly can chain the conditions together like this:

MyObj.public_bids.or(MyObj.outbid_maxbids)

See this answer for more detail: Rails 5: ActiveRecord OR query

这篇关于使用 OR 组合多个命名范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆