Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query for records with empty array with Rails and Postgres array type?

How can I query for all records with an empty array, using the Postgres array data type?

 create_table "users", force: :cascade do |t|
   t.string   "email", limit: 255, default: "",null: false
   t.string   "roles", default: [], array: true
 end

I want to query for all records with an empty roles array.

Tried User.where("roles @> ?", '{}') but that did not work (returned 0 records).

like image 389
chrismanderson Avatar asked Nov 30 '22 16:11

chrismanderson


2 Answers

Here is the syntax you can use:

User.where("roles = '{}'")
like image 196
Petr Gazarov Avatar answered Dec 04 '22 06:12

Petr Gazarov


You can also do: User.where(roles: [])

I'm using Rails 5.2 (although the syntax may have been introduced earlier). I realize this is an old question, but in case anyone finds it from a Google search (like me).

like image 22
Joshua Brian Davis Avatar answered Dec 04 '22 05:12

Joshua Brian Davis