Rails - 作用域上的逻辑运算符,可能吗?

Rails - Logical Operator on Scopes, is it possible?

我有一个 class 表示具有 2 个范围的游戏(比赛):

  scope :home_lineuped, ->() { includes(:home_lineup).where(home_lineup: {lineuped: true }) }
  scope :away_lineuped, ->() { includes(:away_lineup).where(away_lineup: {lineuped: true }) }

我想在结果上使用逻辑运算符 Not And 创建一个新范围,是否可行?

编辑:我是什么意思?

想象一下: Match.All 给我匹配 ID,1, 2, 3, 4, 56;

Match.home_lineuped 给我匹配 ID,1、26;

Match.away_lineuped 给我匹配 ID 3、46;

(Match.home_lineuped AND Match.away_lineuped)的结果是:6.

因此:Not (Match.home_lineuped AND Match.away_lineuped) 将导致匹配 ID:1、2、3、4、5

结束编辑

此致,

大卫

根据您使用的 Rails 版本,ActiveRecord 确实有一个 not 方法。希望对您有所帮助。

你的意思是Match.home_lineuped & Match.away_lineupedMatch.all - (Match.home_lineuped & Match.away_lineuped)

或创建新范围

scope :home_lineuped_and_away_lineuped, ->() { includes(:home_lineup, :away_lineup).where(home_lineups: {lineuped: true }, away_lineups: {lineuped: true }) }

scope :not_home_lineuped_and_away_lineuped, ->() { includes(:home_lineup, :away_lineup).where.not(home_lineups: {lineuped: true }, away_lineups: {lineuped: true }) }

scope :home_lineuped, -> { includes(:home_lineup).where(home_lineup: {lineuped: true }) }
scope :away_lineuped, -> { includes(:away_lineup).where(away_lineup: {lineuped: true }) }

您可以像这样为 AND 逻辑一个接一个地调用作用域:

Match.home_lineuped.away_lineuped

但是如果你需要范围,你可以将两个范围合并为:

scope :home_and_lineuped, -> do
  includes(:home_lineup, :away_lineup).
    where(home_lineup: {lineuped: true }, away_lineup: {lineuped: true })
end

对于相反的逻辑 (NOT AND),您可以使用 not:

scope :no_home_away_lineuped, -> do
  includes(:home_lineup, :away_lineup).
    where.not(home_lineup: {lineuped: true }, away_lineup: {lineuped: true })
end