alopez02
alopez02

Reputation: 1524

OR operator inside a Where Active Record Query

So inside a Where Active Record(AR) query you can do:

game_stickers.where('stickers.name != ?', 'Ban')

But how can you test matches against multiple strings with an OR operator without doing something like:

game_stickers.where('stickers.name != ? OR stickers.name != ?', 'Ban', 'Closed')

or without reverting to something like [see note below]:

game_stickers.where.not(stickers.name: ['Ban','Closed','Block'])

NOTE:

The reason I do not want to go with the last alternative is because I'm using some joins and references in my queries that (as far as I can see) do not play nicely with this option. The context code goes something like:

game_stickers_and_stickers = game_stickers.includes(:sticker)
game_stickers_and_stickers.where('stickers.name = ?', 'Ban').references(:stickers).where(placement_side: side)    

Maybe a you can advise on the optimal way to do this query.

Upvotes: 1

Views: 181

Answers (1)

Ursus
Ursus

Reputation: 30071

Note: it seems to me you want an AND between those conditions, not an OR. Think about it. Anyway, try this one

game_stickers_and_stickers = game_stickers.includes(:sticker)
game_stickers_and_stickers.where.not(stickers: {name: ['Ban','Closed','Block']}).where(placement_side: side) 

that condition fragment should be converted to the SQL

WHERE stickers.name NOT IN ('Ban', 'Closed', 'Block')

Upvotes: 1

Related Questions