Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 5, scope opposite to another scope

Is there any way in Rails 5 that I can use the opposite (negation) of a scope? For example, given I have the following scope

scope :missing_coordinates, -> { where(latitude: [nil, '']).or(where(longitude: [nil, ''])) }

is there any way I can use the opposite of that scope like:

Places.not(missing_coordinates)

which would return the ones that have both the latitude and longitude?

like image 694
Leticia Esperon Avatar asked Sep 06 '25 09:09

Leticia Esperon


1 Answers

How about creating a method that takes the entire collection, and subtracts the missing_coordinates.

self.not_missing_coordinates
    Places.all - Places.missing_coordinates
end

This lets you call Places.not_missing_coordinates. I looked around the docs and couldn't find anything quite like negation of a scope in the way you've described.

like image 128
Joseph Cho Avatar answered Sep 08 '25 23:09

Joseph Cho