5

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.

strivedi183
  • 4,749
  • 2
  • 31
  • 38
Zack Herbert
  • 942
  • 1
  • 16
  • 39
  • See my answer to the same question [here](http://stackoverflow.com/a/40269481/1876622). Also note similar questions [here](http://stackoverflow.com/questions/1482940/) and [here](http://stackoverflow.com/questions/16381619/) – HeyZiko Oct 26 '16 at 20:54

2 Answers2

3

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

Community
  • 1
  • 1
Ryenski
  • 9,582
  • 3
  • 43
  • 47
1

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))
Community
  • 1
  • 1
Uzbekjon
  • 11,655
  • 3
  • 37
  • 54