“活动记录查询”中的“或”运算符

问题描述 投票:1回答:1

因此,在Where Active Record(AR)查询中,您可以执行以下操作:

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

但是,如何使用OR运算符测试与多个字符串的匹配,而不执行以下操作:

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

或者不回复[见下面的注释]:

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

注意:

我不想使用最后一个替代方案的原因是因为我在我的查询中使用了一些joinsreferences(据我所见)不能很好地使用此选项。上下文代码类似于:

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

也许您可以建议进行此查询的最佳方式。

ruby-on-rails rails-activerecord
1个回答
1
投票

注意:在我看来,你想要在这些条件之间进行AND,而不是OR。想一想。无论如何,试试这个

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

该条件片段应该转换为SQL

WHERE stickers.name NOT IN ('Ban', 'Closed', 'Block')
© www.soinside.com 2019 - 2024. All rights reserved.