Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to negate a scope in Rails 3?

I have the following scope for my class called Collection:

scope :with_missing_coins, joins(:coins).where("coins.is_missing = ?", true) 

I can run Collection.with_missing_coins.count and get a result back -- it works great! Currently, if I want to get collections without missing coins, I add another scope:

scope :without_missing_coins, joins(:coins).where("coins.is_missing = ?", false) 

I find myself writing a lot of these "opposite" scopes. Is it possible to get the opposite of a scope without sacrificing readability or resorting to a lambda/method (that takes true or false as a parameter)?

Something like this:

Collection.!with_missing_coins 
like image 247
Yuval Karmi Avatar asked Aug 14 '11 00:08

Yuval Karmi


1 Answers

In Rails 4.2, you can do:

scope :original, -> { ... original scope definition ... } scope :not_original, -> { where.not(id: original) } 

It'll use a subquery.

like image 117
Bill Lipa Avatar answered Sep 20 '22 19:09

Bill Lipa