Combining multiple named scopes with OR

浪子不回头ぞ 提交于 2019-11-28 14:08:15
Uzbekjon

Rails 4 and older do not support OR query "natively". Looks like it will be introduced in Rails 5.

For now, you would have to use SQL with .where method:

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

But, in your case, you are selecting using IN and = queries and the first field is in both scopes. So, it would not make much sense. Anyway, if you really have to, you might get away with this:

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

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!