ruby-on-railsrubyrails-activerecordscopes

Rails - Logical Operator on Scopes, is it possible?


I have a class that represents a game (match) with 2 scopes:

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

I would like to create a new scope with the logical operator Not And on the results, is it possible?

EDIT: What do I mean?

Imagine that: Match.All gives me matches with ID, 1, 2, 3, 4, 5 and 6;

Match.home_lineuped gives me matches with ID, 1, 2 and 6;

Match.away_lineuped gives me matches with ID 3, 4 and 6;

The result of: (Match.home_lineuped AND Match.away_lineuped) is: 6.

Therefore: Not (Match.home_lineuped AND Match.away_lineuped) will result in matches with ID: 1, 2, 3, 4, and 5.

End EDIT

Best Regards,

David


Solution

  • Your meaning are Match.home_lineuped & Match.away_lineuped and Match.all - (Match.home_lineuped & Match.away_lineuped).

    Or create new scope

    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 }) }