【问题标题】:Combining multiple named scopes with OR将多个命名范围与 OR 组合
【发布时间】:2016-09-23 12:49:03
【问题描述】:

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

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)

我无法确定如何将它们OR 组合在一起或合并到一个范围内。有什么建议/指导吗?我希望将它们组合到一个范围内。

【问题讨论】:

  • 查看我对同一问题的回答here。还要注意类似的问题here 和here

标签: ruby-on-rails ruby rails-activerecord named-scope


【解决方案1】:

Rails 4 及更早版本不支持“本机”查询 OR。看起来它将在 Rails 5 中引入。

现在,您必须将 SQL 与 .where 方法一起使用:

YourModel.where('field1 = ? OR field2 = ?', 1, 2)

但是,在您的情况下,您选择使用 IN 和 = 查询,并且第一个字段在两个范围内。所以,这没有多大意义。无论如何,如果你真的需要,你可能会逃跑with this:

data = YourModel.public_bids.outbid_maxbids
YourModel.where(data.where_values.inject(:or))

【讨论】:

    【解决方案2】:

    我没有尝试在作用域中使用or,但您可以使用 Rails 5 的新 or 方法将作用域链接在一起,如下所示:

    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))
    }
    

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

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

    MyObj.public_bids.or(MyObj.outbid_maxbids)
    

    更多详情请参阅此答案:Rails 5: ActiveRecord OR query

    【讨论】:

    • 很遗憾我们还没有升级到 5 :(
    • 那么什么是滞留?它几乎没有测试版! ;)
    猜你喜欢
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2012-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-03
    • 2014-05-30
    相关资源
    最近更新 更多