Julien Fouilhé
Julien Fouilhé

Reputation: 2658

Mongoid : Array contains element or is empty

I want to make a request which returns elements from my collection if a string is in an array or if the array is empty. I tried the following:

Collection.all_of(or: [{ assets: my_asset }, { assets: [] } ])

But this doesn't work.

This works but not for the empty arrays:

Collection.where(assets: my_asset)

Upvotes: 1

Views: 811

Answers (2)

a14m
a14m

Reputation: 8055

I prefer using

Collection.where(:assets.in => [[], my_asset])

Upvotes: 5

Teguh Syahmar
Teguh Syahmar

Reputation: 136

try using any_of

Collection.any_of({ assets: my_asset }, { assets: [] })

Upvotes: 2

Related Questions