Search code examples
ruby-on-railspostgresql-9.1hstore

Return records that don't have specific key - Rails4 HStore Postgresql query


I have a model Task

t.string   "name"
t.hstore   "actions"

Example:

#<Task id: 1, name: "first", actions: {"today"=>"9"}, 
#<Task id: 2, name: "second", actions: {"yesterday"=>"1"}, 
#<Task id: 3, name: "third", actions: nil,
#<Task id: 4, name: "four", actions: {"today"=>"11"},

I need to find all records where actions: nil, :today<10 and key :today not present. It is 1,2,3 task.

Task.where("actions -> 'today' < '10'") - it return only first task.
Task.where("actions -> 'today' < '10' OR actions IS NULL")  - it return 1 and 3 records.

How i can find all records which do not have the key :today in action?


Solution

  • From here, according to your question:

    Task.where("actions IS NULL OR EXIST(actions, 'today') = FALSE")
    

    and according to your comments:

    Task.where("actions -> 'today' < '10' OR actions IS NULL OR EXIST(actions, 'today') = FALSE")